Laravel 使用 max 和 group by 查询

Laravel query with max and group by

我需要在 Laravel 5.1 中创建一个 select 查询,通过常规 SQL 创建它不会有任何问题,我想知道你是否可以帮我把它写在 Laravel.

我创建了这个查询来获取所有拥有卡车、拖车和 delivery_date 等于特定日期(来自 $week_array)的用户。它正在运行,但缺少一些组件

$RS = $this->instance->user()
        ->with(['driver.delivery' => function($query) use ($week_array) {
           $query->where('delivery_date', [Carbon\Carbon::parse($week_array['date'])->toDateTimeString()]);
             }])
        ->with(['driver.trailer', 'driver.truck', 'driver.trailer.trailerType'])->get();

我需要排除那些最大交货日期等于或大于上面查询中 selected 交货日期的司机。这是我需要 plug-in 到 laravel.

的正常查询

换句话说,我需要将以下查询(简化)转换为 Laravel:

SELECT 
    *
FROM
    USERS
        INNER JOIN
    DRIVERS ON DRIVERS.user_id = USERS.id
        INNER JOIN
    DELIVERIES ON DELIVERIES.driver_id = DRIVERS.id
WHERE
    1 = 1
        AND DELIVERIES.driver_id NOT IN (SELECT 
            driver_id
        FROM
            DELIVERIES
        GROUP BY driver_id
        HAVING MAX(delivery_date) >= '2016-05-10')

您正在寻找 whereHas。尝试:

$date = Carbon\Carbon::parse($week_array['date'])->toDateTimeString();

$RS = $this->instance->user()
    ->with(['driver.delivery' => function($query) use ($date) {
        $query->where('delivery_date', [$date]);
    }])
    ->with(['driver.trailer', 'driver.truck', 'driver.trailer.trailerType'])
    ->whereHas('driver.delivery', function($query) use ($date) {
        return $query->where('delivery_date', '>', $date);
    }, '=', 0)
    ->get();

还可以尝试通过将 ->get() 替换为 ->toSql() 并使用 dd 辅助函数来验证查询是否正确。