lundi 16 avril 2018

Laravel 5.5 - whereIn and whereNotIn in same eloquent query?

I have two tables where I need to pluck the valid ids (those that match the $ids array) that exist in TableA AND must ensure they don't exist in TableB. It can be done in two queries easily, but I am trying to do it with a single query to be more efficient:

$ids = ['a1','b2','c3'];

// Table A (id, building_name)  (a1, adam)  (b2, barney)  (c3, castor) 
// Table B (id, building_id)     (1, a1)     (2, b2)

Here is my attempt at this that doesn't work properly:

$finalIdsArray = TableAModel::whereIn('tableA.id', $ids)
                            ->whereNotIn('tableB.building_id', $ids)
                            ->pluck('tableA.id');

Ideally, the query should return ['c3'], since it exists in TableA and does not exist in TableB

Any idea how to get it to work correctly?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire