0
私は2つのテーブル:users, comments
を持っています。各ユーザーの平均値を数える方法は?
各ユーザーにはいくつかのコメントがあります。私は、ユーザー情報とフィールドavg_rate
$users = User:with('comments')->get();
どのように私は、フィールドでの平均値をカウントすることができcomments.rate
where users.id = comments.user_id
:
私は、などの要求を行います
->avg()
を使用しようとしましたが、1行しか返しません。
は私が独自のソリューションを持っているが、私はモデルで、このコードを移動する欲求を持っている:
{{$users->reviewsAverage()->first()->avg("rate")}}
モデル:
public function reviewsAverage()
{
return $this->hasMany('App\Review', 'user_id', 'id'); //->first()->avg('rate');
}
[Laravel:ネストされたhasMany関係(hasManyThrough)の平均を取得する方法](http://stackoverflow.com/questions/27698690/laravel-how-to-get-average-on-nested-hasmany -relationships-hasmanythrough) –