Home > database >  What is the difference between using where() clause With() and wherehas() in relationship model
What is the difference between using where() clause With() and wherehas() in relationship model

Time:09-26

I have two relationship table. I used with using where to filter records as well as i used wherehas using where to filter records. But can't find the differences between both

CodePudding user response:

maybe you can see this documentation:

https://laravel.com/docs/9.x/eloquent-relationships#main-content

CodePudding user response:

If you use where(condition)->with(relation) the query will return the records where condition matches and the relation data if any. Wherase if you use where(condition)->whereHas(relation) the query will return the records where condition matches and where there exists a relation

CodePudding user response:

When you use with() with where() condition, you are applying the condition only on the main table not on the related table, but when you use whereHas() this will apply the condition on the relationship, not on the main table. e.g

1) User::with("post")->where('id', 1)->first();
2) User::whereHas("post", function (Builder $query) {
       $query->where('status', 1);
   })->get();

First will fetch the user who has the user id 1, while second will fetch all the users with posts whose status is published

  • Related