Filter query by count associated data (Cakephp 3)

I want to do a query on “Articles” but I only want the “Articles” wich have 2 or more “Comments”. So I have to count “Comments” and use the count result on where clause.

I know the next code is wrong but it would be something like:

$articles = $this->Articles->find();

$articles->matching('Comments', function ($q) {
    $commentsCount = $q->func()->count('Comments.id');   
    return $q->where($commentsCount . ' >= ' => 2);
});

I can´t find any information about this.

Thanks for the help.

Not a direct answer but…

This might be a good time to consider the CounterCache behavior.

It’s possible your currently strategy could become very costly in the future. CounterCache would store the count of comments in the article and the query would then be trivial.

1 Like