我有一个帖子和喜欢的系统(与模型正确链接)。而且我想获得热门的热门帖子。
在查看CakePHP的文档之后,我在1.2 doc中发现了一些内容:counterCache
。但是,它似乎不再适用于CakePHP 2.x。
那么,你有一个解决方案来获得最受欢迎的帖子吗?
这些表非常基础:id和为每个表创建并与post_id链接为喜欢,这里是likes
表:
========================================
|| *id* | created | post_id | user_id ||
========================================
答案 0 :(得分:0)
强制加入帖子和喜欢并查询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);
答案 1 :(得分:0)
您可以使用CounterCache实现此目的,但这意味着将HABTM替换为“hasMany through”
你会有这样的事情:
<?php
class Post extends AppModel {
public $hasMany = array('Like');
// Note that the "posts" table must have a "like_count" integer field
}
class Like extends AppModel {
public $belongsTo = array(
'User',
'Post' => array('counterCache' => true)
);
}
class User extends AppModel {
public $hasMany = array('Like');
}