CounterCache in cake php

I want to show the total number of comments for a specific post on my blog. There are "posts" and "comments" in my database. Now I am a little confused about using counterCache. First I created a field in the "post database", namely "comment_count", and then added the counterCache key to the post model.

var $hasMany = array('Comment'=>array('counterCache'=>true));

      

But it didn't work. I also tried to go the other way around, that is, by creating a field in the cooments table and adding a counterCache key to the template. But that didn't work either. What am I missing here? Can I display the number of comments using find ('count')? or is there any other way to achieve this?

+2


source to share


5 answers


Are you sure you are using counterCache

correctly? counterCache

and your own solution is somewhat unrelated.

3.7.4.1.1 counterCache - cache your counter ()

This feature helps you cache the amount of related data. Rather than counting records manually via find ('count'), the model itself keeps track of any addition / deletion to the associated $ hasMany model and increments / decrements the allocated integer field in the parent table of the models.

...

class Image extends AppModel {
    var $belongsTo = array(
        'ImageAlbum' => array('counterCache' => true)
    );
}

      

From now on, every time you add or remove an image associated with ImageAlbum, the number inside ImageAlbum.image_count

is automatically adjusted.



In other words, it is designed in such a way that you do not need to $this->Model->find('count')

manually, and it will only change when you add or remove entries. In your case, you have to add the field comment_count

to your post model (as you do), but then specify belongsTo => Post, counterCache => true

in the comments model. The reason is that whenever the comment model changes (adds / removes) it has to update counterCache

in the Post model.

Hope it helps.

+4


source


you are using counterCache in the right way. But try clearing all files (not directories!) In / app / tmp / cache /



0


source


I don't think counterCache can be used in relation $hasMany

, only on $belongsTo

.

0


source


Is there a way to initialize CounterCache on existing data? I refactor my code to use it and indeed if I insert a record it will update the data, but until then it will show 0, which breaks other functionality. I was thinking about writing a script to work, but thought there might be a trick?

0


source


Guys, I figured it out. Write the following code in the action view of the message controller, install it, and then repeat it in the view file. Works great
$counts = $this->Post->Comment
>find('count',array('conditions'=>array('Comment.post_id'=>$post['Post']['id'])));

      

-6


source







All Articles