CakePHP:如何计算查找中hasMany记录的数量?

atp*_*atp 4 mysql cakephp mysql-error-1111 cakephp-1.3

我有两个型号,PosthasMany Comment.如何选择Post少于两个的所有Comment

我试着用find'fields'=>array('COUNT(Comment.id) as numComments','Post.*'),(然后做numComments < 2'conditions').但是,我收到了一个Unknown column 'Comment.id' in 'field list'错误.

谢谢!

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

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
Run Code Online (Sandbox Code Playgroud)

但是我#1111 - Invalid use of group functionCOUNT功能出错了.

编辑:已解决,使用HAVING COUNT而不是WHERE COUNT.

Azi*_*ziz 17

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

将comment_count字段添加到帖子中

这就是全部:-)