Reputation: 13
I want to join right (employees
) table only when left (purchases
) table's employee_id
is NOT NULL
but the query returning empty result set if the employee_id
is NULL
.
$data = DB::table('purchases')
->join('demands', 'purchases.demand_id', 'demands.id')
->join('fiscal_years', 'purchases.fiscal_year_id', 'fiscal_years.id')
->join('employees', function ($join){
$join->on('purchases.employee_id', 'employees.id')
->where('purchases.employee_id', '!=', null);
})
->select('purchases.*', 'demands.code', 'fiscal_years.year', 'employees.name')
->get();
Upvotes: 1
Views: 545
Reputation: 671
Try to use leftJoin. It will join employees if they are.
$data = DB::table('purchases')
->join('demands', 'purchases.demand_id', 'demands.id')
->join('fiscal_years', 'purchases.fiscal_year_id', 'fiscal_years.id')
->leftJoin('employees', function ($join){
$join->on('purchases.employee_id', 'employees.id')
->where('purchases.employee_id', '!=', null);
})
->select('purchases.*', 'demands.code', 'fiscal_years.year', 'employees.name')
->get();
Upvotes: 1