Call to a member function addEagerConstraints() on string

房东的猫 提交于 2020-06-29 04:05:14

问题


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.


回答1:


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



回答2:


The error clearly states that trader_ratings have already calculated the avg and is no longer instance of builder that you would need for eager loading. so may be do some thing as below, (not tested the code, just from top of my head)

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


来源:https://stackoverflow.com/questions/59897448/call-to-a-member-function-addeagerconstraints-on-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!