在字符串上调用成员函数addEagerConstraints() [英] Call to a member function addEagerConstraints() on string
问题描述
我想计算嵌套变形关系列的平均值。
模型函数 >
公共函数trader_ratings()
{
return $ this-> morphMany( TraderRatings :: class,'rateable')
-> select('rateable_id','rateable_type','rating')
-> avg('rating');
}
具有延迟加载的控制器
< pre class = lang-php prettyprint-override>
$ 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
而是给出错误。 / p>
因为 with()
需要获得关系。 addEagerConstraints 是从源代码。当您使用急切加载时,您的关系生成器将调用 addEagerConstraints
。
但是,您的关系方法将返回字符串( avg()
的结果)而不是词形关系。因此会发生错误。
您可以更改方法,例如:
公共函数trader_ratings()
{
return $ this-> morphMany(TraderRatings :: class,'rateable')-> select('*',DB: :raw('AVG(rating)AS avg_rating'));
}
I want to calculate the average of the column of nested morph relation.
Model Function
public function trader_ratings()
{
return $this->morphMany(TraderRatings::class, 'rateable')
->select('rateable_id', 'rateable_type', 'rating')
->avg('rating');
}
Controller with lazy loading
$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();
It is not calculating the avg
but giving the error.
Because with()
need to get the relationship. addEagerConstraints is from source code. When you use eager loading, Your relationship builder will call addEagerConstraints
.
However, your relationship method is return the string(the result of avg()
) instead of morph relationship. So the error occurs.
You can change your method like:
public function trader_ratings()
{
return $this->morphMany(TraderRatings::class, 'rateable')->select('*', DB::raw('AVG(rating) AS avg_rating'));
}
这篇关于在字符串上调用成员函数addEagerConstraints()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!