CakePHP:如何计算找到的hasMany记录的数量? [英] CakePHP: How do I count the number of hasMany records in a find?

查看:160
本文介绍了CakePHP:如何计算找到的hasMany记录的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型, Post hasMany 注释。如何选择所有

$ b

我尝试使用 find 'fields'=> array('COUNT(Comment.id)as numComments','Post 。*')(然后在'conditions'中执行 numComments <2 >)。但是,我在字段列表错误中得到未知列Comment.id。



谢谢! / p>

编辑:我已经得到CakePHP生成这个查询:

  SELECT`Post`。*,FROM` posts` AS` Post` 
LEFT JOIN注释AS`Comment` ON(`Post`.`id` =`Comment`.`text_request_id`)
WHERE COUNT (`Comment`.`id`)< 2
GROUP BY`Comment`.`post_id`
LIMIT 10

但我收到一个错误#1111 - COUNT 函数上的组函数无效。



EDIT:
已解决,请使用HAVING COUNT而不是WHERE COUNT。

解决方案

  class Post extends AppModel 
{
var $ name =Post;
var $ hasMany = array('Comment'=> array('counterCache'=> true));
}

向帖子中添加comment_count字段



这是所有: - )


I have two models, Post hasMany Comment. How do I select all Post that have less than two Comment?

I tried using a find with 'fields'=>array('COUNT(Comment.id) as numComments','Post.*'), (and then doing a numComments < 2 in 'conditions'). But, I get a Unknown column 'Comment.id' in 'field list' error.

Thanks!

EDIT: I've gotten CakePHP to generate this query:

SELECT `Post`.*, FROM `posts` AS `Post` 
    LEFT JOIN comments AS `Comment` ON (`Post`.`id` = `Comment`.`text_request_id`)  
    WHERE COUNT(`Comment`.`id`) < 2 
    GROUP BY `Comment`.`post_id` 
    LIMIT 10

But I get an error #1111 - Invalid use of group function on the COUNT function.

EDIT: Resolved, use the HAVING COUNT instead of WHERE COUNT.

解决方案

class Post extends AppModel
{
    var $name = "Post";
    var $hasMany = array('Comment'=>array('counterCache'=>true));
}

add comment_count fields into posts

an that's all :-)

这篇关于CakePHP:如何计算找到的hasMany记录的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆