In the recipe, Performing GROUP and COUNT queries, we learnt how to add computed SQL expressions to a find
operation. Some of these expressions may be needed regularly for a model, introducing the need for virtual fields.
Using virtual fields, we get the resulting values of our SQL expressions as if they were real fields of our models. They allow us to get the same results shown in the previous recipe in a much more transparent way, without needing the override of afterFind
.
We need some sample models and data to work with. Follow the Getting ready section of the recipe, Performing GROUP and COUNT queries.
Open the Post
model and add the virtualfields
definition shown as follows:
<?php
class Post extends AppModel {
public $belongsTo = array('Blog');
public $virtualFields = array(
'period' => 'CONCAT(YEAR(Post.created), \'-\', MONTH(Post.created))',
'total' => 'COUNT(*)'
);
}
?>
To obtain a count of all the posts per blog, grouped...