Laravel Eloquent select all rows with max created_at

后端 未结 2 672
轮回少年
轮回少年 2020-11-30 15:56

I have a table that contains:

id  seller_id   amount   created_at
1   10          100      2017-06-01 00:00:00
2   15          250      2017-06-01 00:00:00
.         


        
相关标签:
2条回答
  • 2020-11-30 15:58

    This worked:

    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();
    
    0 讨论(0)
  • 2020-11-30 16:08

    To get latest record for each seller_id you can use following query

    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
    

    Using query builder you might rewrite it as

    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();
    
    0 讨论(0)
提交回复
热议问题