CakePHP has counterCache functionality for this exact purpose.
Ensure your posts table contains a 'comment_count' field.
Then add the counterCache key to the Comment model's belongsTo Post settings.
// app/models/comment.php
var $belongsTo = array(
'Post' => array(
'counterCache' => true
)
);
CakePHP will now automatically increment / decrement the Post.comment_count field everytime a comment belonging to that post is added or deleted.
To get the top 10 most commented posts:
// app/models/post.php
function getTopCommentedPosts($limit = 10) {
return $this->find('all', array(
'order' => 'Post.comment_count DESC',
'limit' => $limit
));
}
Then call this method from any controller action that requires this data. If from a controller other than the PostsController use:
$this->set('posts', ClassRegistry::init('Post')->getTopCommentedPosts());