views:

191

answers:

2

Hello

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:

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

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.

A: 

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.

deceze
CakePHP 1.3 unfortunately doesn't have the 'having' index in the array.
Jasie
You're right. -_-;; This may be one case where writing SQL by hand is preferred. Alternatively, @Aziz' suggestion of count-caching is actually the better and faster (query-wise) way.
deceze
+5  A: 
class Post extends AppModel
{
    var $name = "Post";
    var $hasMany = array('Comment'=>array('counterCache'=>true));
}

add comment_count fields into posts

an that's all :-)

Aziz