Laravel Eloquent get results grouped by days

前端 未结 14 598
一整个雨季
一整个雨季 2020-12-02 06:44

I currently have a table of page_views that records one row for each time a visitor accesses a page, recording the user\'s ip/id and the id of the page itself. I should add

14条回答
  •  时光取名叫无心
    2020-12-02 07:32

    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();
    

    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"')
                                ));
    

提交回复
热议问题