我有以下DB结构:
user_talk
- id
user_talk_feedback
- user_talk_id
- rating [from 1 to 5]
我有以下关系:
// on UserTalk model
public function feedbacks(): HasMany
{
return $this->hasMany(UserTalkFeedback::class);
}
我目前有一个获取UserTalk
的端点,我想为每个UserTalk
平均加载。有办法吗?
到目前为止,我已经尝试过:
// on UserTalk model
public function averageRating(): HasMany
{
return $this->hasMany(UserTalkFeedback::class);
}
$userTalks = UserTalk::with([
'averageRating' => function ($query) {
$query->avg('rating');
}
])
但我没有得到平均收视率被热切加载。
2条答案
按热度按时间pkwftd7m1#
尝试使用withAvg():
sgtfey8w2#
尝试在模型上使用访问器,如下所示:
protected $appends = ['avg_rating'];
public function getAvgRatingAttribute()
{
return $this->feedbacks->avg('rating');
}
$userTalks = UserTalk::with(['feedbacks'])->get();