我的数据库中有 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 获得平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
MySQLi准备好的语句&foreach 循环MySQLi prepared statement amp; foreach loop(MySQLi准备好的语句amp;foreach 循环)
mysqli_insert_id() 是从整个服务器还是从同一用户获Is mysqli_insert_id() gets record from whole server or from same user?(mysqli_insert_id() 是从整个服务器还是从同一用户获取记录?)
PHP MySQLi 无法识别登录信息PHP MySQLi doesn#39;t recognize login info(PHP MySQLi 无法识别登录信息)
mysqli_select_db() 需要 2 个参数mysqli_select_db() expects exactly 2 parameters(mysqli_select_db() 需要 2 个参数)
Php mysql pdo 查询:用查询结果填充变量Php mysql pdo query: fill up variable with query result(Php mysql pdo 查询:用查询结果填充变量)
MySQLI 28000/1045 用户“root"@“localhost"的访问MySQLI 28000/1045 Access denied for user #39;root#39;@#39;localhost#39;(MySQLI 28000/1045 用户“root@“localhost的访问被拒绝)