How to get average of column values in laravel

别说谁变了你拦得住时间么 提交于 2019-11-27 07:42:12

问题


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 it added and divided by the rows there are.

How do I do it in laravel. I can do it in plain php but I want to learn it in laravel.


回答1:


Try this :

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

" Model " will replace with your model name




回答2:


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.




回答3:


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



回答4:


// 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



来源:https://stackoverflow.com/questions/42529067/how-to-get-average-of-column-values-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!