使用max和group by的Laravel查询

时间:2016-04-21 23:31:49

标签: php mysql laravel eloquent laravel-5.1

我需要在Laravel 5.1中创建一个选择查询,通过常规SQL创建我没有问题,我想知道你是否可以帮我在Laravel中编写它。

我创建了这个查询,让所有拥有truck,trailer和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();

我需要排除那些MAX交付日期等于或大于上述查询中所选交付日期的驱动程序。这是我需要插入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')

1 个答案:

答案 0 :(得分:2)

您正在寻找NUMERIC。尝试:

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()辅助函数来验证查询的正确性。