问题
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