如何获得一个“平均值”在一个渴望加载关系laravel

nhhxz33t  于 2023-05-08  发布在  其他
关注(0)|答案(2)|浏览(133)

我有以下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');
  }
])

但我没有得到平均收视率被热切加载。

pkwftd7m

pkwftd7m1#

尝试使用withAvg():

$userTalks = UserTalk::withAvg('feedbacks', 'rating')->paginate();
sgtfey8w

sgtfey8w2#

尝试在模型上使用访问器,如下所示:

protected $appends = ['avg_rating'];

public function getAvgRatingAttribute()
{
return $this->feedbacks->avg('rating');
}

$userTalks = UserTalk::with(['feedbacks'])->get();

相关问题