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

时间:2010-06-26 08:06:21

标签: mysql cakephp cakephp-1.3 mysql-error-1111

我有两个模型,Post hasMany 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

但我在#1111 - Invalid use of group function函数上收到错误COUNT

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

3 个答案:

答案 0 :(得分:17)

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

将comment_count字段添加到帖子中

这就是全部: - )

答案 1 :(得分:1)

在原始SQL中,查询看起来像这样:

SELECT Post.*
FROM Post LEFT JOIN Comment ON Post.id = Comment.post_id
GROUP BY Comment.post_id
HAVING COUNT(Comment.id) < 2

其中大部分都很容易翻译成Cake:

array(
    'having' => array('COUNT(Comment.id) <' => 2),
    'group'  => array('Comment.post_id')
)

Cake不会自动加入hasMany表,这是您需要手动执行的操作。有关详细信息,请查看the documentation

编辑:

您可以执行以下having子句:

array(
    'group' => 'Comment.post_id HAVING COUNT(Comment.id) < 2'
)

限制只有string才适用于小组,不能在没有小组的情况下完成。 Cake 3可能包含更多SQL语法,例如HAVING

答案 2 :(得分:0)