Laravel 5.3 Eloquent Join table 具有多个条件的 join having count

Laravel 5.3 Eloquent Join table with multiple condition join having count

我对左连接 table 有疑问,它使用计数到 select main table 以如下所述的条件显示:

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

我试过使用这样的 eloquent 代码,但是 DB::raw 在 $join 函数中不起作用

$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();

如何使用 laravel eloquent 实现此查询?提前致谢!

使用这个:

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