开发者

CakePHP: How do I count the number of hasMany records in a find?

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:

SE开发者_JAVA百科LECT `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 :-)


In raw SQL, the query would look something like this:

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

Most of these are easily translated to Cake:

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

Cake does not automatically join hasMany tables though, this is something you'll need to do manually. Have a look at the documentation for the details.

Edit:

You can do a having clause as follows:

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

The limitations are string only for the group and cant be done without the group by. Cake 3 will probably include more SQL syntax such as HAVING


If anyone interested: here's the doc about counterCache http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto and here's more about adding multiple counterCache fields http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#multiple-countercache

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜