How to get average of column values in laravel

后端 未结 5 464
误落风尘
误落风尘 2020-12-06 17:09

Lets say I have this column

star
----
1    
3    
3    
1    
2    
5    
3

It has seven rows and there are integer values! I want to have

相关标签:
5条回答
  • 2020-12-06 17:26

    If you have more columns you can use the native function of the database manager using DB::raw

    $products = DB::table('products')
                     ->select('id','name',DB::raw('round(AVG(quantity),0) as quantity'))
                     ->groupBy('id','name')
                     ->get();
    
    0 讨论(0)
  • 2020-12-06 17:29

    // let's say the Model name is Review and Table name is reviews, you have a 'star' column on it

    $value = Reviews::all();
    $value->avg('star');
    
    return view('page.name')->withValue($value);
    

    // it will calculate an average of star column

    0 讨论(0)
  • 2020-12-06 17:37

    If you want to do it with the query builder you can use aggregate methods like avg:

    $avg_stars = DB::table('your_table')
                    ->avg('star');
    

    Laravel 5 docs about aggregates.

    0 讨论(0)
  • 2020-12-06 17:38

    Table::Where('column', $case)->pluck('column')->avg()

    0 讨论(0)
  • 2020-12-06 17:44

    Try this :

    $avgStar = Model::avg('star');
    

    " Model " will replace with your model name

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