php 如何获得laravel中列值的平均值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42529067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get average of column values in laravel
提问by Alen
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.
我如何在 Laravel 中做到这一点。我可以用普通的 php 来完成,但我想在 Laravel 中学习它。
回答by Muthu17
Try this :
尝试这个 :
$avgStar = Model::avg('star');
" Model " will replace with your model name
“型号”将替换为您的型号名称
回答by Troyer
If you want to do it with the query builder you can use aggregate methods like avg
:
如果你想用查询构建器来做,你可以使用聚合方法,如avg
:
$avg_stars = DB::table('your_table')
->avg('star');
Laravel 5 docsabout aggregates.
Laravel 5 文档关于聚合。
回答by Vladimir Salguero
If you have more columns you can use the native function of the database manager using DB::raw
如果您有更多列,您可以使用数据库管理器的本机功能 DB::raw
$products = DB::table('products')
->select('id','name',DB::raw('round(AVG(quantity),0) as quantity'))
->groupBy('id','name')
->get();
回答by Kerols Monsef
Table::Where('column', $case)->pluck('column')->avg()
Table::Where('column', $case)->pluck('column')->avg()
回答by niwesh shrestha
// 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
// 它将计算星列的平均值