tags:

views:

362

answers:

3

I want to display the total number of comments for a particular post in my blog. I have 'posts' and 'comments' tables in my database. Now, I am a bit confused about using counterCache. I first created a field in the 'posts database', namely, 'comment_count' and then I added the counterCache key in the post model.

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

But this was not working. I also tried to go the other way round, i.e by creating a field in the cooments table and the adding the counterCache key to the model. But this was also not working. What am I missing here??Can I display the number of comments using find('count')?? or is there any other way to achieve this?

A: 

Guys, I figured it out. Write the following code in the view action of posts controller, set it and then echo it out in the view file. Works perfectly

$counts = $this->Post->Comment
>find('count',array('conditions'=>array('Comment.post_id'=>$post['Post']['id'])));
Learner
A: 

Are you sure you're using counterCache correctly? counterCache and your own solution are somewhat unrelated.

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.

...

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

From now on, every time you add or remove a Image associated to ImageAlbum, the number within ImageAlbum.image_count is adjusted automatically.

In other words, it's designed so you don't have to $this->Model->find('count') manually and it'll only change when adding or deleting entries. In your case, you should add a comment_count field to your Post model (as you did), but then specify belongsTo => Post, counterCache => true in the Comment model. The reason being that whenever the Comment model changes (add/delete), it has to update the counterCache in the Post model.

Hope that helps.

deceze
Actually I dropped the idea of using counterCache after I got tired of it. The find('count') works perfectly for me. But, thanks for your answer. It has cleared my confusion about using counterCache :)
Learner
A: 

you are using counterCache in correct way. But try to clear all files (not directories!) in /app/tmp/cache/

Aziz