我想计算嵌套变形关系列的平均值。
型号功能
public function trader_ratings()
{
return $this->morphMany(TraderRatings::class, 'rateable')
->select('rateable_id', 'rateable_type', 'rating')
->avg('rating');
}
延迟加载的控制器
$user = auth('api')->user();
$user_id = $user->id;
$customer_classes = CustomerClassBooking::with([
'trader_class',
'trader_class.trader_ratings',
'vendor',
])
->where('customer_id', $user_id)
->where('status', 'Accepted-paid')
->get();
它不是在计算avg
而是给出了错误。
因为with()
需要得到关系。addEagerConstraints来自源代码。当您使用即时加载时,您的关系生成器将调用addEagerConstraints
。
但是,您的关系方法是返回字符串(的结果avg()
)而不是变体关系。因此会发生错误。
您可以像这样更改方法:
public function trader_ratings()
{
return $this->morphMany(TraderRatings::class, 'rateable')->select('*', DB::raw('AVG(rating) AS avg_rating'));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句