2016-10-07 5 views
0

私は2つのテーブル:users, commentsを持っています。各ユーザーの平均値を数える方法は?

各ユーザーにはいくつかのコメントがあります。私は、ユーザー情報とフィールドavg_rate

wityhすべての行でコレクションを取得する必要があり、結果では

$users = User:with('comments')->get(); 

どのように私は、フィールドでの平均値をカウントすることができcomments.ratewhere 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'); 
    } 
+0

[Laravel:ネストされたhasMany関係(hasManyThrough)の平均を取得する方法](http://stackoverflow.com/questions/27698690/laravel-how-to-get-average-on-nested-hasmany -relationships-hasmanythrough) –

答えて

0

は2つの機能の関係のための1つを持って、彼他の平均的な機能のために

public function comments() 
{ 
    return $this->hasManyThrough('App\Comment', 'id'); 
} 

public function averageRating() 
{ 
    return $this->comments()->selectRaw('avg(rate) as average_rate, comment_id') 
          ->groupBy('comment_id'); 
} 

そして、先に行くと、この

ようなクエリ
foreach($users as $user){ 
    $rate = $user->averageRate(); 
} 
関連する問題