Wednesday, March 1, 2017

laravel, group by category and select the record with the minimum price

I have models Book and BookCategory

How do I select the cheapest book in every category?

Book table:
| 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

The selection should be :
| id | name | price | book_category_id |
| 1 | test | 10 | 1
| 2 | test | 15 | 3
| 6 | test | 11 | 2

I've tried:

$books = Book::groupBy("book_category_id")->orderBy("price")->get()

But the output is not the minimum price row.




via Barjas

Advertisement