What Is Querying Relationship Absence 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 Absence in Laravel

What Is Querying Relationship Absence In Laravel Framework

Querying Relationship Absence

When accessing the records for a model, you may wish to limit your results based on the absence of a relationship. For example, imagine you want to retrieve all blog posts that don't have any comments. To do so, you may pass the name of the relationship to the doesntHave and orDoesntHave methods:

  • doesntHave and specify the boolean operator

Example(1) 
Implement code in DemoController

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


If you need even more power, you may use the whereDoesntHave and orWhereDoesntHave methods to put "where" conditions on your doesntHave queries. These methods allows you to add customized constraints to a relationship constraint, such as checking the content of a comment:
 

use Illuminate\Database\Eloquent\Builder;

$posts = App\Post::whereDoesntHave('comments', function (Builder $query) {
    $query->where('content', 'like', 'foo%');
})->get();
 


You may use "dot" notation to execute a query against a nested relationship. For example, the following query will retrieve all posts that do not have comments and posts that have comments from authors that are not banned:
 

use Illuminate\Database\Eloquent\Builder;

$posts = App\Post::whereDoesntHave('comments.author', function (Builder $query) {
    $query->where('banned', 0);
})->get();
 

Single query we can also usedoesntHave to get all the jobs that are not applied by the user.

Related Post