2017-03-01 49 views
0

我有模型BookBookCategorylaravel,按类别组和最低价格

如何选择在每个类别中最便宜的书选择记录?

书籍表:

| 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查询生成器?

+0

您提供的代码的结果是什么? – milo526

+0

其获得每个组的第一个记录,在我的这种情况下,它得到的书ID:1,2和4 – Zorox

回答

0

您需要执行像this post这样的子查询。试试这个:

$books = Book::from(DB::raw("SELECT * FROM books order by price asc")) 
      ->groupBy("book_category_id")->get(); 

请注意,这是一个MySQL唯一的解决办法,因为在MySQL中你允许非集合非组的列。如果您需要为其他数据库执行此操作,则需要在子查询上执行内连接

+0

这返回完全像我的代码。它会返回每个组的第一条记录+额外提交的min_price。 (min_price,没有必要返回记录的价格 – Zorox

+0

查看我更新的答案 – Paras

+0

还是,即使重新排列,结果也不是最低的记录 – Zorox