如何在 Laravel 5 中使用 orderBy Desc 获得平均值

2021-12-26 00:00:00 php mysql laravel laravel-5 eloquent

我的数据库中有 2 个表.

I have 2 tables in my database.

booksratings

书籍id, name

评级

idbook_idrating

我已经为这些模型设置了很多关系.

i have set has many relationship for these models.

所以在 Book 模型中 -

So in Book model -

public function ratings()
{
    return $this->hasMany('AppRating');
}

Rating 模型 -

public function book()
{
    return $this->belongsTo('AppBook');
}

现在我想获取所有具有平均评分但按高评分排序的书籍.

Now i want to fetch all books with there average rating but order by high rating.

所以我先给书评分高,然后评分低.

so i high rated books first and then low ratings.

那么我如何加入 2 个表来实现这个结果.

So How i can join 2 tables to achieve this result.

谢谢.

推荐答案

您可以使用修改后的 withCount():

You can use a modified withCount():

$books = Book::withCount(['ratings as average_rating' => function($query) {
    $query->select(DB::raw('coalesce(avg(rating),0)'));
}])->orderByDesc('average_rating')->get();

相关文章