强制加入帖子和点赞,并查询COUNT()
点赞数、GROUP BY
计数器、ORDER BY
计数器降序和LIMIT x
顶部 x;
试试这个,我假设模型命名为Post
,Like
和一个连接表:
$options = array();
$options['joins'][] = array('table' => 'likes_posts', 'alias' => 'LikePost', 'conditions' => array('LikePost.post_id = Post.id'));
$options['joins'][] = array('table' => 'likes', 'alias' => 'Like', 'conditions' => array('LikePost.like_id = Like.id'));
$options['fields'] = array('COUNT(Like.id) AS counter', 'Post.*');
$options['group'] = 'Like.id';
$options['limit'] = 1; //you could easily get the top 3, top 5, top 10...
$options['order'] = 'counter DESC';
$data = $this->Post->find('all', $options);
$this->set('data', $data);