skip to Main Content

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

3

Answers


  1. 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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. 1). Where()

    $table::with("relation-name")->where(condition)->get();
    

    simple get the data with this "relation-name" against this where(condition)
    there is no condition apply on the 2nd table (relationship table);

    2). Wherehas()

    User::where Has("relation-name", function (Builder $query) {
           $query->where('status', 1);
       })->get();
    

    wherehas() apply condition on the 2nd table (relationship table);

    My understanding and also have practiced this way in my projects.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search