【发布时间】:2018-04-12 07:37:37
【问题描述】:
我对左连接表有疑问,它使用计数来选择要显示的主表,条件如下:
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
我尝试过使用这样的雄辩代码,但是 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 实现这个查询?提前致谢!
【问题讨论】:
-
你可以试试
$join->whereRaw('device.deleted_at is null'); -
@haidang 是的,我认为你的答案是正确的。非常感谢,海棠!
-
一点也不,我的朋友。
标签: php laravel join eloquent having-clause