在浮动LARAVEL上调用成员函数addEagerConstraints()

在浮动LARAVEL上调用成员函数addEagerConstraints()

问题描述:

我的目标是对可用课程进行平均评估.但是,当我尝试对课程进行平均评估时,会抛出一个错误,提示"message": "Call to a member function addEagerConstraints() on float"

My objective is to get average review of the courses available. But when i am trying to get the average review of the course its throwing me an error saying "message": "Call to a member function addEagerConstraints() on float"

我的课程模型

 public function rating(){
    return $this->hasMany(Rating::class);
}
public function averageRating(){
    return round($this->rating()->avg('ratings'),1);
}

评分模型

 public function user(){
        return $this->belongsTo(User::class);
    }
    public function course(){
        return $this->belongsTo(Course::class);
    }

我的控制器

$result = Course::with('averageRating')->get();

我希望它能提供课程详细信息以及每门课程的平均评分,但是会引发错误. 谁能帮帮我吗?? 谢谢

I was expecting it to give Course detail along with average rating of each course but it throwing error. Can anyone please help me?? Thank you

AverageRating方法不是关系,您不能使用它,例如关系. 如果您希望获得平均评分,请将averageRating设置为附加属性.

AverageRating method isn't a relation and you can't use it such as relation. If you want have average rating , set averageRating to appended attributes.

Course.php:

Course.php:

protected $appends = [
    'average-rating'
];

function getAverageRatingAttribute(){
    return round($this->rating()->avg('ratings'),1);
}