Laravel按日期时间格式按小时分组

时间:2018-07-31 09:33:37

标签: sql laravel

如何在一天中的某个小时对网站上的“注册”进行分组?

我已经尝试过了,但是没有用。

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

我收到一个错误:

  

无法访问空属性。

我希望查询结果超过0。

4 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

使用:

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

答案 3 :(得分:0)

我已经尝试过您的答案了。但事实证明,该错误是由于我的原始用户缺少别名引起的。

df.limit('10')

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