laravel,按类别分组并选择最低价格的记录

时间:2017-03-01 19:26:50

标签: laravel laravel-5.4

我有模型BookBookCategory

如何选择每个类别中最便宜的图书?

书桌:

| 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查询构建器?

1 个答案:

答案 0 :(得分:0)

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

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

请注意,这是一个仅限mysql的解决方案,因为在mysql中,您不允许聚合非分组列。如果需要为另一个DB执行此操作,则需要在子查询

上执行内部联接