在浮动LARAVEL上调用成员函数addEagerConstraints() [英] Call to a member function addEagerConstraints() on float LARAVEL

查看:272
本文介绍了在浮动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);
}

这篇关于在浮动LARAVEL上调用成员函数addEagerConstraints()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆