skip to Main Content

I have the following DB structure:

user_talk
- id

user_talk_feedback
- user_talk_id
- rating [from 1 to 5]

I have the following relationships:

// on UserTalk model
public function feedbacks(): HasMany
{
  return $this->hasMany(UserTalkFeedback::class);
}

I currently have an endpoint that fetches the UserTalk and I would like to eager load the average for each UserTalk. Is there a way to do it?

So far I have tried:

// on UserTalk model
public function averageRating(): HasMany
{
  return $this->hasMany(UserTalkFeedback::class);
}
$userTalks = UserTalk::with([
  'averageRating' => function ($query) {
    $query->avg('rating');
  }
])

But I’m not getting the average of ratings being eager loaded.

2

Answers


  1. Try using accessor on the model as follows:

    ```
    protected $appends = ['avg_rating'];
    
    public function getAvgRatingAttribute() 
    { 
        return $this->feedbacks->avg('rating');
    }
     
     $userTalks = UserTalk::with(['feedbacks'])->get();
    
    ```
    
    Login or Signup to reply.
  2. Try using withAvg():

    $userTalks = UserTalk::withAvg('feedbacks', 'rating')->paginate();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search