我有模型Book
和BookCategory
laravel,按類別組和最低價格
如何選擇在每個類別中最便宜的書選擇記錄?
書籍表:
| id | name | price | book_category_id |
| 1 | test | 10 | 1
| 2 | test | 15 | 3
| 3 | test | 75 | 1
| 4 | test | 25 | 2
| 5 | test | 19 | 1
| 6 | test | 11 | 2
| 7 | test | 10 | 1
的選擇應該是:
| id | name | price | book_category_id |
| 1 | test | 10 | 1
| 2 | test | 15 | 3
| 6 | test | 11 | 2
我已經試過:
$books = Book::groupBy("book_category_id")->orderBy("price")->get()
但產量並不是最低價格一行。
有什麼想法嗎?
編輯:
我找到了這個網頁: https://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/
它90%的SQL
SELECT *
FROM books
WHERE price = (SELECT MIN(price) FROM books AS u WHERE u.book_category_id= books.book_category_id)
GROUP BY books.book_category_id
解決如何將它轉換爲laravel查詢生成器?
您提供的代碼的結果是什麼? – milo526
其獲得每個組的第一個記錄,在我的這種情況下,它得到的書ID:1,2和4 – Zorox