左连接不为空

Left join on not null

如何在 Eloquent 查询构建器中对 null 进行左连接?

我有 2 个模型:Customer (customers table) 和 Appointment (appointments table)。一个客户可以有 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;

查询 1查询 2 之间存在细微差别:

查询 1 包括已软删除所有约会的客户(这正是我想要的)。 查询 2 没有。

有没有一种方法可以在 Eloquent 中做到这一点而不求助于子查询?此查询的输出转到 'index' 视图,每页有 100(或更多)条记录 ,因此我不想不必要地减慢它的速度。我还希望用户能够按最大日期 排序 结果。

我唯一合理的选择是普通的 'raw sql query' 吗?

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');