Reputation: 201
I have question about left join table which using having count to select main table to be shown with the condition described as below:
select b.id, b.location_name, b.box_identity
from box b
left join device d on b.id = d.box_id
and d.deleted_at is null
group by b.id, b.location_name, b.box_identity
having count(d.*) < COALESCE(b.device_slot, 3)
order by b.id desc
i have tried using eloquent code like this, but DB::raw is not working in $join function
$boxes = Box::leftJoin('device', function($join) {
$join->on('box.id', '=', 'device.box_id');
$join->on(DB::raw('device.deleted_at is null'));
})
->select('box.id', 'box.box_identity', 'box.location_name')
->groupBy('box.id', 'box.box_identity', 'box.location_name')
->havingRaw('COUNT(device.*) < COALESCE(box.device_slot, 3)')
->orderBy('box.id', 'desc')
->get();
How can i achieve this query using laravel eloquent? Thanks in advance!
Upvotes: 2
Views: 5699
Reputation: 2738
use this :
$boxes = Box::leftJoin('device', function($join) {
$join->on('box.id', '=', 'device.box_id');
$join->whereRaw('device.deleted_at is null');
})
Upvotes: 4