1
votes

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!

1
You can try $join->whereRaw('device.deleted_at is null');haidang
@haidang yeah, i think your answer is the right one. thanks a lot, haidang!Rakaziwi
Not at all, my friend.haidang

1 Answers

3
votes

use this :

$boxes = Box::leftJoin('device', function($join) {
    $join->on('box.id', '=', 'device.box_id');
    $join->whereRaw('device.deleted_at is null');
})