Laravel Eloquent: how to use “where” with WithCount to select Models whose count is larger than a number

Viewed 67

Suppose I have two tables: posts and tags. I want to eager load all the tags with posts whose post count is larger than 10. How would I do it?

I tried the following but not work:

Tag::withCount('posts')
   ->where('posts_count', '>' , 10)
   ->get();

It gives me the following error:

Column not found: 1054 Unknown column 'posts_count' in 'where clause' (SQL: select `tags`.*, (select count(*) from `posts` inner join `post_tag` on `posts`.`id` = `post_tag`.`post_id` where `tags`.`id` = `post_tag`.`tag_id`) as `posts_count` from `tags` where `posts_count` > 1 order by `posts_count` desc)
1 Answers

try this:

Tag::withCount('posts')->having('posts_count', '>' , 10)->get();

If you want to filter on aggregates, you need to use having.

Related