代码之家  ›  专栏  ›  技术社区  ›  rxmnnxfpvg

cakephp:我如何计算查找中有多少条记录?

  •  4
  • rxmnnxfpvg  · 技术社区  · 14 年前

    我有两个型号, Post 哈萨克斯坦 Comment . How do I select all 少于两个 评论 ?

    我试着用 find 具有 'fields'=>array('COUNT(Comment.id) as numComments','Post.*') , (and then doing a 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 功能。

    编辑: Resolved, use the HAVING COUNT instead of WHERE COUNT.

    3 回复  |  直到 9 年前
        1
  •  17
  •   Aziz    14 年前
    class Post extends AppModel
    {
        var $name = "Post";
        var $hasMany = array('Comment'=>array('counterCache'=>true));
    }
    

    在帖子中添加注释计数字段

    这就是全部:

        2
  •  1
  •   dogmatic69 ornoone    12 年前

    在原始SQL中,查询如下所示:

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

    其中大部分很容易翻译成蛋糕:

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

    尽管cake不会自动加入很多表,但这是您需要手动执行的操作。看一看 the documentation 细节问题。

    编辑:

    你可以做 having 条款如下:

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

    限制是 string 只针对群体,不做小组就不行。蛋糕3可能会包括更多 SQL 语法如 HAVING

        3
  •  0
  •   raumus    11 年前