Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eloquent where not in query?

I'm trying to build the following sql query with eloquent. The query gives me all records from table_a which are in the list of ids and do not appear in table_b.

select * from table_a 
where id in (1,2,3)
   and id not in 
      (select tablea_id from table_b 
       where tablea_id in (1,2,3))

So how do I do it in eloquent ? I want to avoid using a raw query.

//does not work
TableA::whereIn('id',$ids)
   ->whereNotIn('id', TableB::select('tabla_id')->whereIn($ids));
like image 340
c4pone Avatar asked Dec 19 '22 05:12

c4pone


1 Answers

To run a subquery you have to pass a closure:

TableA::whereIn('id',$ids)
      ->whereNotIn('id', function($q){
          $q->select('tabla_id')
            ->from('tableb');
            // more where conditions
      })
      ->get();
like image 133
lukasgeiter Avatar answered Mar 19 '23 05:03

lukasgeiter