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

问题描述 投票:1回答:2

我的目标是对可用课程进行平均评估。但是,当我试图得到该课程的平均审查时,它给我一个错误说"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();

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

php mysql laravel laravel-5 eloquent
2个回答
3
投票

AverageRating方法不是关系,你不能使用它如关系。如果您想要具有平均评级,请将averageRating设置为附加属性。

Course.php:

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

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

0
投票

with用于急切加载实现,因此Laravel期望在尝试急切加载时返回一个雄辩的模型。但是你传递一个浮点值(使用round())。

一个解决方案是简单地加载:

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

然后执行以下操作访问平均评分:

foreach($result as $r){
    echo $r->averageRating;
}
© www.soinside.com 2019 - 2024. All rights reserved.