3.7.4.1.1 counterCache - Cache your count()
This function helps you cache the count of related data. Instead of counting the records manually via find('count'), the model itself tracks any addition/deleting towards the associated $hasMany model and increases/decreases a dedicated integer field within the parent model table.
The name of the field consists of the singular model name followed by a underscore and the word "count".
Let's say you have a model called "ImageAlbum" and a model called "Image", you would add an INT-field to the "image_album" table and name it "image_count". Or if your names are more complex, here is another example: With "BlogEntry" and "BlogEntryComment", the name of the field would be "blog_entry_comment_count" and needs to be added to "blog_entries".
Once you have added the counter field you are good to activate this functionality by adding the "counterCache" key to the "$belongsTo" association array and set the value to "true".
class ImageAlbum extends AppModel {
var $hasMany = array(
'Image'
);
}
class Image extends AppModel {
var $belongsTo = array(
'ImageAlbum' => array('counterCache' => true)
);
}
class ImageAlbum extends AppModel {var $hasMany = array('Image');}class Image extends AppModel {var $belongsTo = array('ImageAlbum' => array('counterCache' => true));}
Now every time you add a new "Image" to "ImageAlbum" the number within "image_count" will increase (or decrease if you do a delete).
