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)
    );
}
  1. class ImageAlbum extends AppModel {
  2. var $hasMany = array(
  3. 'Image'
  4. );
  5. }
  6. class Image extends AppModel {
  7. var $belongsTo = array(
  8. 'ImageAlbum' => array('counterCache' => true)
  9. );
  10. }

Now every time you add a new "Image" to "ImageAlbum" the number within "image_count" will increase (or decrease if you do a delete).