Laravel Eloquent get results grouped by days

前端 未结 14 501
一整个雨季
一整个雨季 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:18

    Warning: untested code.

    $dailyData = DB::table('page_views')
        ->select('created_at', DB::raw('count(*) as views'))
        ->groupBy('created_at')
        ->get();
    
    0 讨论(0)
  • 2020-12-02 07:20

    You can filter the results based on formatted date using mysql (See here for Mysql/Mariadb help) and use something like this in laravel-5.4:

    Model::selectRaw("COUNT(*) views, DATE_FORMAT(created_at, '%Y %m %e') date")
        ->groupBy('date')
        ->get();
    
    0 讨论(0)
  • 2020-12-02 07:22

    To group data according to DATE instead of DATETIME, you can use CAST function.

    $visitorTraffic = PageView::select('id', 'title', 'created_at')
    ->get()
    ->groupBy(DB::raw('CAST(created_at AS DATE)'));
    
    0 讨论(0)
  • 2020-12-02 07:23

    I know this is an OLD Question and there are multiple answers. How ever according to the docs and my experience on laravel below is the good "Eloquent way" of handling things

    In your model, add a mutator/Getter like this

    public function getCreatedAtTimeAttribute()
    {
       return $this->created_at->toDateString();
    }
    

    Another way is to cast the columns in your model, populate the $cast array

    $casts = [
       'created_at' => 'string'
    ]
    

    The catch here is that you won't be able to use the Carbon on this model again since Eloquent will always cast the column into string

    Hope it helps :)

    0 讨论(0)
  • 2020-12-02 07:26

    I had same problem, I'm currently using Laravel 5.3.

    I use DATE_FORMAT()

    ->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))
    

    Hopefully this will help you.

    0 讨论(0)
  • 2020-12-02 07:26
    PageView::select('id','title', DB::raw('DATE(created_at) as date'))
              ->get()
              ->groupBy('date');
    
    0 讨论(0)
提交回复
热议问题