2
votes

I have two tables, topics and posts. I want to get only the topics that have no posts.

I tried to use order by, but then I have topics that have no posts and also some that have posts, so it's wrong.

Topic::where('locale', $locale)
    ->withCount('posts')
    ->orderBy('posts_count', 'ASC')
    ->paginate(15);
2
What are you trying to get? All topics that don't have any posts?theblackips

2 Answers

4
votes

If you are trying to get all topics that do not have posts, try this:

Topic::doesntHave('posts')->paginate(15);

If you want to filter for a certain (maximum) count of posts, do this:

Topic::has('posts', '<=', $count)->paginate(15);
1
votes

If you are trying to get the topics without any posts, you can use doesntHave if your models are setup properly:

$topicsWithoutPosts= Topic::doesntHave('posts')->where('locale',$locale)->paginate(15);