I have two models. Lets say they are "Posts" and "Comments". In an admin view for Posts, I want to display how many comments are on that post. I am confused on where to put the code. In the controller or the view? I would like it to be in the controller.
A:
Yes,you're right.You should get data in the controller,then display it in the view.And what you describe in your question is exactly like the example in the cookbook.Assume you have related then with Post hasMany Comment
,you can find the count using:
$comment_count = $this->Post->Comment->find('count',array('conditions'=>array('Comment.post_id'=>$postid)));
SpawnCxy
2010-04-29 00:34:48
+1
A:
Another option is to cache your count. With this approach, you'd add the field comment_count
to your posts
table, then modify your Comment
model's belongsTo
association like this:
class Comment extends AppModel
{
var $belongsTo = array(
'Post' => array( 'counterCache' => true )
);
}
Anytime a new Comment
record is created, the comment_count
of the associated Post
record is incremented, and decremented anytime an associated Comment
is deleted.
Daniel Wright
2010-04-29 02:21:54