本文介绍了如何使用雄辩平均多列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找相关模型的多个列的平均值,如下所示:

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?

谢谢

推荐答案

避免多个查询,您可以在 doc / eloquent>口述,如下所示:

To avoid multiple queries you can use a raw database expression within Eloquent as shown below:

$averages = $this->reviews()
    ->select(DB::raw('avg(communication) c, avg(friendliness) f'))
    ->first();

echo $averages->c;
echo $averages->f;

由于集合函数名称 avg 已被识别由Laravel所有支持的数据库,这不会是一件大事。

Since the aggregate function name avg is recognized by all supported database by Laravel, this will not be a big deal.

这篇关于如何使用雄辩平均多列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 19:57