本文介紹了如何在 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 獲得平均值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!