0

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');
    }
Samed
  • 9
  • 2
  • Possible duplicate of [Laravel: how to get average on nested hasMany relationships (hasManyThrough)](http://stackoverflow.com/questions/27698690/laravel-how-to-get-average-on-nested-hasmany-relationships-hasmanythrough) – Ivanka Todorova Oct 07 '16 at 09:19

1 Answers1

0

Have two functions one for the relationship and he other for the average function

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');
}

Then go ahead and query like this

foreach($users as $user){
    $rate = $user->averageRate();
}
Timothy Radier
  • 323
  • 4
  • 15