Laravel Eloquent选择max created_at的所有行

时间:2017-12-24 08:13:32

标签: php mysql laravel greatest-n-per-group

我有一张包含以下内容的表:

id  seller_id   amount   created_at
1   10          100      2017-06-01 00:00:00
2   15          250      2017-06-01 00:00:00
....
154 10          10000    2017-12-24 00:00:00
255 15          25000    2017-12-24 00:00:00

我想获取每个Seller_id的所有最新行。我可以得到这样的最新一行:

$sales = Snapshot::where('seller_id', '=', 15)
    ->orderBy('created_at', 'DESC')
    ->first();

如何只为每位卖家提供最新一行?

2 个答案:

答案 0 :(得分:3)

要获取每个seller_id的最新记录,您可以使用以下查询

select s.*
from snapshot s
left join snapshot s1 on s.seller_id = s1.seller_id
and s.created_at < s1.created_at
where s1.seller_id is null

使用查询构建器,您可以将其重写为

DB::table('snapshot as s')
  ->select('s.*')
  ->leftJoin('snapshot as s1', function ($join) {
        $join->on('s.seller_id', '=', 's1.seller_id')
             ->whereRaw(DB::raw('s.created_at < s1.created_at'));
   })
  ->whereNull('s1.seller_id')
  ->get();

答案 1 :(得分:0)

这有效:

DB::table('snapshot as s')
  ->select('s.*')
  ->leftJoin('snapshot as s1', function ($join) {
        $join->on('s.seller_id', '=', 's1.seller_id');
        $join->on('s.created_at', '<', 's1.created_at');
   })
  ->whereNull('s1.seller_id')
  ->get();