Skip to content
Advertisement

Call to a member function addEagerConstraints() on string

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.

Advertisement

Answer

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'));
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement