【问题标题】:CakePHP: How do I count the number of hasMany records in a find?CakePHP:如何计算查找中的 hasMany 记录数?
【发布时间】:2010-06-26 08:06:20
【问题描述】:

我有两个模型,Post hasMany Comment。如何选择少于两个Comment 的所有Post

我尝试使用find'fields'=>array('COUNT(Comment.id) as numComments','Post.*'),(然后在'conditions' 中使用numComments < 2)。但是,我收到 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

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

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

【问题讨论】:

  • 是的,对不起,我的 SQL 有点生疏了,我正要建议 HAVING。 :)

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


【解决方案1】:
class Post extends AppModel
{
    var $name = "Post";
    var $hasMany = array('Comment'=>array('counterCache'=>true));
}

将comment_count 字段添加到帖子中

仅此而已:-)

【讨论】:

  • 只是让你知道:这个答案结束了两天的沮丧搜索如何做到这一点。 +1000 给你!
【解决方案2】:

在原始 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 仅适用于组,没有 group by 就无法完成。 Cake 3 可能会包含更多SQL 语法,例如HAVING

【讨论】:

  • CakePHP 1.3 不幸的是在数组中没有“有”索引。
  • 你是对的。 -_-;;这可能是首选手动编写 SQL 的一种情况。或者,@Aziz 对计数缓存的建议实际上是更好更快(查询方式)的方式。
【解决方案3】:

【讨论】:

    猜你喜欢
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    相关资源
    最近更新 更多