简体   繁体   中英

Converting Query Builder to Eloquent in Laravel

I have a user table, and a review table.

In my review table, there's a "star_rating" column.

I can get the average "star_rating" score for a user with the following query:

$star_rating = Review::where('artist_id', $user->id)->avg('star_rating');

However, this doesn't work too well when I'm printing out a bunch of users in blade (I want to show their average star_rating next to their names).

That's why I'd like to have a function in my User.php model that I can call to get a user's average star rating.

public function getAvgStarRating() {
    return $this-> // logic goes here //;
}

Add this relation in your User model:

public function reviews()
{
    return $this->hasMany(Review::class, 'artist_id', 'id');
}

Then add this method to get average of star ratings

public function getAvgStarRating()
{
    return $this->reivews->avg('star_rating');
}

And if you need to display a group of user's rating, first eager load their reviews (it is more efficient)

$users = User::with('reviews')->get();

Then

foreach($users as $user) {
    $user->getAvgStarRating();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM