PHP
Filter Records Based on Related Model Existence
Efficiently query parent models based on the existence or absence of specific related records using Eloquent's `has` and `whereHas` methods.
// Example: Get all users who have at least one post
$usersWithPosts = App\Models\User::has('posts')->get();
// Example: Get all users who have at least one published post
$usersWithPublishedPosts = App\Models\User::whereHas('posts', function ($query) {
$query->where('is_published', true);
})->get();
// Example: Get all posts that do not have any comments
$postsWithoutComments = App\Models\Post::doesntHave('comments')->get();
// Example: Get all posts with comments containing a specific keyword
$postsWithKeywordInComments = App\Models\Post::whereHas('comments', function ($query) {
$query->where('content', 'like', '%keyword%');
})->get();
How it works: Eloquent's `has` and `whereHas` methods are powerful for filtering parent models based on the existence or specific conditions of their related models. `has('relation')` checks if a relationship has at least one related record. `whereHas('relation', function ($query) { ... })` allows you to add further constraints to the related model's query before checking for existence, providing fine-grained control over relationship-based filtering. `doesntHave` works similarly for non-existence queries.