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

為{幸葍}努か 提交于 2019-12-04 11:15:18
class Post extends AppModel
{
    var $name = "Post";
    var $hasMany = array('Comment'=>array('counterCache'=>true));
}

add comment_count fields into posts

an that's all :-)

deceze

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!