laravel 如何使用 Eloquent 平均多列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18307355/
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 average multiple columns using Eloquent?
提问by Russ Back
I'm looking to get the average value across multiple columns on a related model, something like this:
我希望获得相关模型上多列的平均值,如下所示:
$this->reviews()->avg('communication', 'friendliness')
Where communication and friendliness are an array of column names. However it appears the aggregate functions only support single column names, so I'm doing this:
其中交流和友好是一个列名数组。然而,聚合函数似乎只支持单列名称,所以我这样做:
$attributes = array('communication', 'friendliness');
$score = array();
foreach ($attributes as $attribute)
{
$score[] = $this->reviews()->avg($attribute);
}
return round(array_sum($score) / sizeof($attributes), 1);
Which results in multiple queries. Any suggestions for a best practice here?
这会导致多个查询。对这里的最佳实践有什么建议吗?
Thanks
谢谢
回答by Rubens Mariuzzo
To avoid multiple queries you can use a raw database expressionwithin Eloquentas shown below:
为了避免多次查询,您可以在Eloquent 中使用原始数据库表达式,如下所示:
$averages = $this->reviews()
->select(DB::raw('avg(communication) c, avg(friendliness) f'))
->first();
echo $averages->c;
echo $averages->f;
Since the aggregate function name avg
is recognized by all supported database by Laravel, this will not be a big deal.
由于avg
Laravel 支持的所有数据库都可以识别聚合函数名称,因此这不是什么大问题。