【问题标题】:Laravel 5.3 Eloquent Join table with multiple condition join having countLaravel 5.3 Eloquent Join 表与多个条件连接有计数
【发布时间】: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-&gt;whereRaw('device.deleted_at is null');
  • @haidang 是的,我认为你的答案是正确的。非常感谢,海棠!
  • 一点也不,我的朋友。

标签: php laravel join eloquent having-clause


【解决方案1】:

使用这个:

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

【讨论】:

  • 我认为应该使用 $join->on('device.deleted_at','=',DB::raw('NULL'));但是,结果仍然无效。安装了 3 个设备的框仍然显示,它必须不显示。
  • 尝试 DB::enableQueryLog(); dd(DB::getQueryLog());在末尾。然后在这里发布查询
  • 您的查询将在 MySQL 中检查 deleted_at = "NULL" 字符串而不是 deleted_at is null。在这种情况下,必须使用raw query
  • @BRjava 是的,现在这是正确的,就像海当的回答一样
猜你喜欢
  • 2020-06-27
  • 2015-05-17
  • 2020-10-25
  • 2014-01-10
  • 2016-07-22
  • 1970-01-01
  • 2015-02-02
  • 2019-09-06
  • 1970-01-01
相关资源
最近更新 更多