如何在雄辩的查询构建器中对null
进行左联接?
我有2个模型:Customer
(customers
表)和Appointment
(appointments
表)。客户可以有0个或多个约会。客户和约会都可以被软删除。
我想在查询生成器中复制此查询:
查询1 :
SELECT max(a.date) AS max_date, c.* FROM customers AS c
LEFT JOIN appointments AS a ON a.customer_id = c.id AND a.deleted_at IS NULL
WHERE c.deleted_at IS NULL
GROUP BY c.id;
我知道这:
Customer::selectRaw('max(appointments.date) as max_date, customers.*')
->leftJoin('appointments', 'appointments.customer_id', '=', 'customers.id')
->where('appointments.deleted_at')
->groupBy('customers.id');
结果:
查询2 :
SELECT max(a.date) AS max_date, c.* FROM customers AS c
LEFT JOIN appointments AS a ON a.customer_id = c.id
WHERE c.deleted_at IS NULL AND a.deleted_at IS NULL
GROUP BY c.id;
但是 Query 1 和 Query 2 之间存在细微差别:
查询1 包括已删除所有约会的客户(这就是我想要的)。 查询2 不会。
在Eloquent中有没有一种方法可以不诉诸子查询?该查询的输出进入“索引”视图,其中每页有100条(或更多)记录 ,因此我不想不必要地降低它的速度。我还希望用户能够按最大日期对结果进行排序。
我唯一合理的选择是普通的“原始sql查询”吗?
答案 0 :(得分:1)
leftJoin()
接受闭包:
Customer::selectRaw('max(appointments.date) as max_date, customers.*')
->leftJoin('appointments', function($join) {
$join->on('appointments.customer_id', '=', 'customers.id')
->where('appointments.deleted_at');
})
->groupBy('customers.id');