CakePHP 模型:可包含中的 COUNT(*)

2021-12-21 00:00:00 model php cakephp pagination

我有一个 CakePHP 1.3 应用程序并且非常喜欢用于获取数据的可包含行为.

I have a CakePHP 1.3 app and really enjoy the Containable behavior for fetching data.

假设我的帖子与评论是一对多的关系.我使用 Containable 来查询(用于分页)所有帖子和所属评论的列表.但我只对每个帖子有多少评论感兴趣.我没有找到任何方法来实现这个查询,而无需获取所有评论行.我试过了:

Let's assume I have Posts in one-to-many relationship with Comments. I use Containable to query (for pagination) a list of all Posts and the belonging Comments. But I'm only interested in how many Comments each Post has. I did not found any way to achieve this query with containable without fetching all rows of Comments. I tried:

$this->paginate=array(
            'fields' => 'Post.title, Post.created',
            'contain' => array('Comment'=>'COUNT(*) AS count'),
        );

导致模型评论"与模型计数"错误消息无关.

results in 'Model "Comment" is not associated with model "Count"' error message.

$this->paginate=array(
            'fields' => array('Post.title, Post.created'),
            'contain' => array('Comment'=>array('fields'=>'COUNT(*) AS count'),
        );

不起作用,结果集为每个 Post 包含一个空的 Comment 数组,除了最后一个,其中包含计数字段,但包含所有评论的数量,而不仅仅是属于的评论.

does not work, result set contains for each Post an empty Comment array except for the last one, where it contains the count field, but having the number of all comments not just the belonging ones.

我的另一个猜测是

$this->paginate=array(
            'fields' => 'Post.title, Post.created, COUNT(Comment.id)',
            'contain' => array('Comment'=>array('fields'=>''),
        );

但这会导致错误,因为hasMany关系是独立查询的,所以Answer表不在查询Post条目中.如何计算帖子的评论数量?

but this results in an error, because hasMany relationships are queried independently, so the Answer table is not in the query for the Post entries. How can I count the number of Comments a Post has?

推荐答案

嗯,最好的方法是在 posts 中设置一个名为 comment_count 的字段表并将此键添加到评论模型 $belongsTo Post 数组:

Well, the best way to do this is to set up a field called comment_count in the posts table and add this key to the Comment model $belongsTo Post array:

'counterCache' =>真实

每次评论发生任何事情时,相关帖子中的comment_count字段都会更新(实际上,它每次都会重新计数,而不是仅仅添加或删除).

Every time anything will be happening with the comments, the comment_count field in the related post will be updated (actually, it recounts every time, instead of just adding or deleting).

更好,因为当您为用户获取数据时,它的方式会更快,甚至不会触及评论表.由于您使用的是 Containable 行为,我猜您正在寻找速度和轻量级.

It's better, because when you fetch data for the user, its way faster and doesn't even touch the comments table. Since you're using the Containable behaviour I guess speed and lightweight is what you're looking for.

相关文章