What Is Querying Relationship Existence in Laravel Framework

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

Eloquent relationships are defined as methods on your Eloquent model classes. Since, like Eloquent models themselves, relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities.today we are going to discuss about Querying Relationship Existence in Laravel

What Is Querying Relationship Existence in Laravel Framework

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();

Related Post