【问题标题】:Laravel group by Hour from datetime FormatLaravel 按日期时间格式按小时分组
【发布时间】:2019-01-07 15:48:16
【问题描述】:

如何按一天中的时间在我的网站上对“注册”进行分组?

我试过了,但是没有用。

$regs = DB::table('registrations')
       ->select('createddatetime', DB::raw('COUNT(id)'))
       ->groupBy(DB::raw('DATEPART(hour, createddatetime)'), 'createddatetime')
       ->get();

我得到一个错误:

无法访问空属性。

我希望查询的结果超过 0 个。

【问题讨论】:

  • 添加registrations表回答

标签: sql laravel


【解决方案1】:

您可以使用 GroupBy 功能使其正确

$regs = DB::table('registrations')->select('createddatetime', DB::raw('COUNT(id) as count'))->get();
$regs = $regs->groupBy(function($reg){
    return date('H',strtotime($reg->createddatetime));
});
echo '<pre>';
print_r($regs);

【讨论】:

  • createdatetime 不包含在聚合函数或 GROUP BY 子句错误中。
【解决方案2】:

如果你的数据库是mysql,那么你可以这样做

$registrationsByHour = DB::table('registrations')
            ->select(DB::raw('hour(createddatetime)'), DB::raw('COUNT(id)'))
            ->groupBy(DB::raw('hour(createddatetime)'))
            ->get();

【讨论】:

  • 我正在为此使用 Sql Server。
【解决方案3】:

我已经尝试过你的答案。但事实证明,该错误是由 Missing Alias to my raw 引起的。

$regs = DB::table('registrations')
   ->select('createddatetime', DB::raw('COUNT(id) as count'))
   ->groupBy(DB::raw('DATEPART(hour, createddatetime)'), 'createddatetime')
   ->get();

我刚刚添加了别名,它解决了我的问题。不过,非常感谢您的回答。

【讨论】:

    【解决方案4】:

    用途:

    Registration::all()->groupBy(function ($item, $key) {
            return Carbon::parse($item['createddatetime'])->hour;
        });
    

    【讨论】:

    • 这可行,但值得注意的是,这将在集合上执行 groupBy,因此在数据库查询完成后。
    猜你喜欢
    • 1970-01-01
    • 2017-04-14
    • 2020-10-26
    • 2016-09-13
    • 2014-03-28
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多