4
votes

In the Laravel 5 I can find all posts that have at least one comment using has method:

// Retrieve all posts that have at least one comment...
$posts = App\Post::has('comments')->get();

As theres no method like notHas, how can I find all posts that have no comments? (remembering that it's a hasMany relationship)


Reference:

Querying Relationship Existence

http://laravel.com/docs/5.1/eloquent-relationships#querying-relations

2

2 Answers

10
votes

There isn't a notHas() method as far as I'm aware, but finding records with a relationship count less than one usually satisfies this requirement:

$posts = App\Post::has('comments', '<', 1)->get();
7
votes

Old topic but updated answer for those who came from Google like me. Nowadays you can just use doesntHave().

$posts = App\Post::doesntHave('comments')->get();

Reference:

Querying Relationship Absence

https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-absence