Laravel Eloquent with two “WHERE NOT IN” in subquery
Try Something like this:
DB::table('delivery_sap')
->whereNotIn('cust', DB::table('customer')->pluck('cust'))
->whereNotIn('cust_no', DB::table('customer')->pluck('cust_no'))
->select('cust', 'cust_no')
->groupBy('cust', 'cust_no')
->get();
Instead of executing 3 different queries you can use like shown below,
DB::table('delivery_sap')
->whereNotIn('cust', function ($query) {
$query->select('cust_name')->from('customer');
})
->whereNotIn('cust_no', function ($query) {
$query->select('cust_code')->from('customer');
})
->select('cust', 'cust_no')
->distinct('cust')
->get();
This code will give the exact same query which is asked in the question, to check the query, use following code
DB::table('delivery_sap')
->whereNotIn('cust', function ($query) {
$query->select('cust_name')->from('customer');
})
->whereNotIn('cust_no', function ($query) {
$query->select('cust_code')->from('customer');
})
->select('cust', 'cust_no')
->distinct('cust')
->toSql();
Output will be,
select distinct `cust`, `cust_no` from `delivery_sap`
where `cust` not in (select `cust_name` from `customer`)
and `cust_no` not in (select `cust_code` from `customer`)
I corrected the code below pluck('cust') to pluck('cust_name') and pluck('cust_no') to pluck('cust_code') and it works
DB::table('delivery_sap')
->whereNotIn('cust', DB::table('customer')->pluck('cust_name'))
->whereNotIn('cust_no', DB::table('customer')->pluck('cust_code'))
->select('cust', 'cust_no')
->groupBy('cust', 'cust_no')
->get();