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
Try using accessor on the model as follows:
Try using withAvg():