且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel Eloquent按天分组结果

更新时间:2023-01-29 21:32:44

我相信我已经找到了解决方案,关键是mysql中的DATE()函数,它将DateTime转换为Date:

I believe I have found a solution to this, the key is the DATE() function in mysql, which converts a DateTime into just Date:

DB::table('page_views')
      ->select(DB::raw('DATE(created_at) as date'), DB::raw('count(*) as views'))
      ->groupBy('date')
      ->get();

但是,这并不是Laravel Eloquent解决方案,因为这是一个原始查询.以下是我用Eloquent-ish语法得出的结论.第一个where子句使用碳日期进行比较.

However, this is not really an Laravel Eloquent solution, since this is a raw query.The following is what I came up with in Eloquent-ish syntax. The first where clause uses carbon dates to compare.

$visitorTraffic = PageView::where('created_at', '>=', \Carbon\Carbon::now->subMonth())
                            ->groupBy('date')
                            ->orderBy('date', 'DESC')
                            ->get(array(
                                DB::raw('Date(created_at) as date'),
                                DB::raw('COUNT(*) as "views"')
                            ));