How to get average with orderBy Desc in Laravel 5(如何在 Laravel 5 中使用 orderBy Desc 获得平均值)
本文介绍了如何在 Laravel 5 中使用 orderBy Desc 获得平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据库中有 2 个表.
I have 2 tables in my database.
books
和 ratings
在书籍
id
, name
在评级
id
、book_id
、rating
我已经为这些模型设置了很多关系.
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 获得平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何在 Laravel 5 中使用 orderBy Desc 获得平均值


基础教程推荐
猜你喜欢
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- Web 服务器如何处理请求? 2021-01-01
- php中的PDF导出 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- php中的foreach复选框POST 2021-01-01
- 将变量从树枝传递给 js 2022-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01