我的数据库中有三个表。
用户:存储用户信息。
book:存储每本书的信息
book_reviews:存储每个用户对每本书的评论信息(例如总分)。
我想在Laravel中编写一个查询,以检索用户给出的平均总得分最高的图书。
如何使用Eloquent在Laravel中编写以下SQL查询?
SELECT books.*, AVG(book_reviews.overall_point) AS avg_point
FROM books JOIN
book_reviews
ON books.id = book_reviews.book_id
GROUP BY book.id
ORDER BY avg_point DESC
答案 0 :(得分:0)
我认为您可以使用orderByRaw()
方法来实现。通过这种方法,您可以以平均总积分订购图书
Book::select("books.*")
->join("book_reviews br","br.book_id","=","books.id")
->orderByRaw("AVG(br.overall_point) desc")
->groupBy("books.id")
->take(10) # or how many book you want
->get();