我有模型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