Laravel Eloquent get results grouped by days

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

    Like most database problems, they should be solved by using the database.

    Storing the data you want to group by and using indexes you can achieve an efficient and clear method to solve this problem.

    Create the migration

        $table->tinyInteger('activity_year')->unsigned()->index();
        $table->smallInteger('activity_day_of_year')->unsigned()->index();
    

    Update the Model

    <?php
    
    namespace App\Models;
    
      use DB;
      use Carbon\Carbon;
      use Illuminate\Database\Eloquent\Model;
    
      class PageView extends Model
      {
      public function scopePerDay($query){
    
         $query->groupBy('activity_year');
         $query->groupBy('activity_day_of_year');
    
         return $query;
    
      }
    
      public function setUpdatedAt($value)
      {   
        $date = Carbon::now();
    
        $this->activity_year = (int)$date->format('y');
        $this->activity_day_of_year = $date->dayOfYear;
    
        return parent::setUpdatedAt($value);
     }
    

    Usage

       $viewsPerDay = PageView::perDay()->get();
    
    0 讨论(0)
  • 2020-12-02 07:42

    Using Laravel 4.2 without Carbon

    Here's how I grab the recent ten days and count each row with same day created_at timestamp.

    $q = Spins::orderBy('created_at', 'desc')
    ->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))
    ->take(10)
    ->get(array(
          DB::raw('Date(created_at) as date'),
          DB::raw('COUNT(*) as "views"')
      ));
    
    
    foreach ($q as $day) {
    
      echo $day->date. " Views: " . $day->views.'<br>';
    
    }
    

    Hope this helps

    0 讨论(0)
提交回复
热议问题