如何在 Laravel 5 中使用 orderBy Desc 获得平均值 [英] How to get average with orderBy Desc in Laravel 5

查看:43
本文介绍了如何在 Laravel 5 中使用 orderBy Desc 获得平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有 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();

这篇关于如何在 Laravel 5 中使用 orderBy Desc 获得平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆