4

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));
c4pone
  • 777
  • 7
  • 17

1 Answers1

11

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();
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270