繁体   English   中英

在字符串上调用成员函数 addEagerConstraints()

[英]Call to a member function addEagerConstraints() on string

我想计算嵌套变形关系列的平均值。



模型函数

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'));
}

该错误清楚地表明 trader_ratings 已经计算出平均值,并且不再是您需要预加载的构建器实例。 所以可能会做一些如下的事情,(没有测试代码,只是从我的头顶开始)

public function trader_ratings()
{
  return $this->morphMany(TraderRatings::class, 'rateable')->select('rateable_id','rateable_type','rating');
 }


// Then

$customer_classes = CustomerClassBooking::with([
         'trader_class',
         'trader_class.trader_ratings' => function($query`){
            $query->avg('rating)
         },

        ,'vendor'])-> // rest of query

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM