Querying Relationship Existence
When accessing the records for a model, you may wish to limit your results based on the existence of a relationship.
We can check if the eloquoent model has certain relationship or not and fetch the results accordingly while querying upon it, you can do this by two approaches in the Laravel Eloquent.
has
method to check the existence of the relationship
doesntHave
method to check the absence of the relationship.
For example, imagine you want to retrieve all blog posts that have at least one comment. To do so, you may pass the name of the relationship to the has
and orHas
methods:
// Retrieve all posts that have at least one comment...
$posts = App\Post::has('comments')->get();
You may also specify an operator and count to further customize the query:
// Retrieve all posts that have three or more comments...
$posts = App\Post::has('comments', '>=', 3)->get();
Nested has
statements may also be constructed using "dot" notation. For example, you may retrieve all posts that have at least one comment and vote:
// Retrieve posts that have at least one comment with votes...
$posts = App\Post::has('comments.votes')->get();
If you need even more power, you may use the whereHas
and orWhereHas
methods to put "where" conditions on your has
queries. These methods allow you to add customized constraints to a relationship constraint, such as checking the content of a comment:
use Illuminate\Database\Eloquent\Builder;
// Retrieve posts with at least one comment containing words like foo%...
$posts = App\Post::whereHas('comments', function (Builder $query) {
$query->where('content', 'like', 'foo%');
})->get();
// Retrieve posts with at least ten comments containing words like foo%...
$posts = App\Post::whereHas('comments', function (Builder $query) {
$query->where('content', 'like', 'foo%');
}, '>=', 10)->get();