Search code examples
laravelsubquerywhere-in

Laravel WhereIn or Wheren with where


Im trying to design a query, but I have no idea where to start.

I'll type it out how I want it to function.

    Items::whereIn('id',$ids)->orWhereIn('id_2',$ids)->where('type','!=',$type)->get();

Thats how I want it to work, but I know that wont work, because it will just ignore the WHERE type=$type query, because the whereIN's would have already pulled records, that dont adhere to the Where query.

Basically I want the eloquent version of this...

  "SELECT * FROM items WHERE type!=$type AND (id IN (1,2,3) OR id_2 IN(1,2,3))"

Solution

  • What you are attempting to do is to group statements: https://laravel.com/docs/5.3/queries#parameter-grouping

    What you need to do is to make the code something like this:

    Items::where('type', '!=', $type)
      ->where(function ($query) use ($ids) {
          $query->whereIn('id',$ids)
          ->orWhereIn('id_2',$ids);
      })
      ->get();
    

    That way you are grouping the where in clauses.