【问题标题】:How to use aggregate functions on the time of a datetime column with Eloquent?如何在 Eloquent 的日期时间列的时间上使用聚合函数?
【发布时间】:2019-10-25 15:14:43
【问题描述】:

我有以下 SQL 表:

|----------------------------------------------------------| |课程 | |------------------------------------|----------| | BEGIN_DATE(日期时间)| END_DATE(日期时间)| |------------------------------------|----------| | 2019-04-22 10:00:00 | 2019-04-22 12:00:00 | | 2019-04-23 09:00:00 | 2019-04-23 10:00:00 |

使用 Laravel Eloquent,我想获取 BEGIN_DATE 列的所有课程的最小小时数,以及 END_DATE 列的最大小时数。 在这种情况下,我希望09:00:00 用于最短时间,12:00:00 用于最长时间。

我首先尝试了Lesson::min('begin_date')Lesson::max('end_date'),但它显然返回了最小和最大日期时间,而不是时间。

我也试过

Lesson::select('select cast(begin_datetime as time)')
    ->where('season_id', $this->id)->min(time);

但我得到一个 SQL 错误:

'COLUMN NOT FOUND` 用于时间别名。

另外,我更喜欢仅使用 Eloquent 的解决方案,不使用 SQL

我该怎么做?

【问题讨论】:

    标签: php sql laravel datetime eloquent


    【解决方案1】:

    你可以这样做:

    $data = Lesson::selectRaw(
                'min(TIME(begin_date)) as min_time, max(TIME(end_date)) as max_time'
            )
            ->first()
            ->toArray();
    

    这应该返回如下内容:

    dd($data);
    
    => [
         "min_time" => "09:00:00",
         "max_time" => "12:00:00",
       ]
    

    我还希望看到一个 Eloquent 方法(尝试过但失败了,哈哈)。我希望这会有所帮助。

    【讨论】:

    • 完美!非常感谢。
    猜你喜欢
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    相关资源
    最近更新 更多