左连接不为空

ycggw6v2  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(398)

我怎样才能做左连接 null 在雄辩的查询生成器中?
我有两种型号: 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;

但是查询1和查询2之间有一点不同:
查询1包括所有约会都被软删除的客户(这就是我想要的)。查询2不存在。
有没有一种方法可以雄辩地做到这一点,而不诉诸子查询?这个查询的输出转到每页有100条(或更多)记录的“index”视图,所以我不想不必要地减慢它的速度。我还希望用户能够排序的最大日期的结果。
我唯一合理的选择是简单的“原始sql查询”吗?

pgky5nke

pgky5nke1#

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

相关问题