I have two tables: users, comments
.
Each user has some comments.
I do request like as:
$users = User:with('comments')->get();
How can I count the average value in field comments.rate
where users.id = comments.user_id
In result I should get collection with all rows wityh user information and field avg_rate
I tried to use ->avg()
, but it returns only one row, not for each
I have own solution, but I have desire to move this code in model:
{{$users->reviewsAverage()->first()->avg("rate")}}
Model:
public function reviewsAverage()
{
return $this->hasMany('App\Review', 'user_id', 'id'); //->first()->avg('rate');
}