如何在雄辩的laravel中使用group by编写联接查询?

时间:2019-02-23 14:01:24

标签: mysql sql laravel eloquent

我的数据库中有三个表。

用户:存储用户信息。

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

1 个答案:

答案 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();