If you have two tables with a hasOne
or hasMany
relationship between them, and you want to query a row that is missing from the second table, you can use doesntHave()
in Eloquent.
app/Models/Post.php:
public function comments(){ return $this->hasMany(Comment::class);}
Then, somewhere in the Controller:
$posts = Post::doesntHave('comments')->get();
Under the hood, it will perform this SQL query:
select * from posts where not exists ( select * from comments where posts.id = comments.post_id )
It is the opposite of querying the records present in BOTH tables:
Post::has('comments')->get();
Read more in the official Laravel docs.
No comments or questions yet...