最新项目和 GROUP By with Eloquent

Newest items and GROUP By with Eloquent

我有以下价格-table:

shop_id (int)
product_id (int)
price (float)
created (DateTime)

cronjob 每小时检查商店并在这些价格中插入新条目(当前价格)-table。

现在我想显示产品的最新价格。我必须按 shop_id 分组,因为我只想要每个商店的一个价格,但我只想要最新的条目(已创建)。

我可以使用 Eloquent Query-Builder 解决这个问题,还是必须使用原始 SQL?如果列相同,是否可以将原始 SQL 查询的结果传递到模型中?

你可以试试:

Price::select('*', DB::raw('MAX(created_at) as max_created_at'))
      ->groupBy('shop_id')
      ->get()

假设模型名称是 Price

Eloquent(纯粹主义者)方法:

Price::orderBy('created', 'desc')->groupBy('shop_id')
                                 ->get('shop_id', 'price');

参考文献:

https://laravel.com/api/5.3/Illuminate/Database/Query/Builder.html#method_orderBy

https://laravel.com/api/5.3/Illuminate/Database/Query/Builder.html#method_groupBy

https://laravel.com/api/5.3/Illuminate/Database/Query/Builder.html#method_get

*虽然未经测试

问:如果列相同,是否可以将原始 SQL 查询的结果传递到模型中?

答:你可以传给Model's contructor - but it might need model's field to be fillable - or hydrate a model。或者,只需像键控数组一样访问它,即。 $something[0]['price'] <-- 假设价格列为价格数组。

我在没有QueryBuilder 的情况下解决了这个问题。相反,我使用原始 SQL-语句并使用模型的 hydrateRaw()-函数生成模型-class.

$prices = Price::hydrateRaw( 'SELECT p.*
      FROM prices p
      INNER JOIN (
        SELECT shop_id, max(created_at) AS max_ca
        FROM prices p1
        GROUP BY shop_id
      ) m ON p.shop_id = m.shop_id AND p.created_at = m.max_ca');