Call to a member function addEagerConstraints() on float LARAVEL

断了今生、忘了曾经 提交于 2020-05-28 03:19:16

问题


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"

My Course Model

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

Rating model

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

My Controller

$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


回答1:


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:

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

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



回答2:


The with is used to eager load realtions and hence Laravel expects an eloquent model to be returned when trying to eager load. But you are passing a float value (using round()).

A solution is to simply eager load:

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

and then access average rating by doing:

foreach($result as $r){
    echo $r->averageRating;
}


来源:https://stackoverflow.com/questions/48108935/call-to-a-member-function-addeagerconstraints-on-float-laravel

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