Get most recent row with group by and Laravel

前端 未结 5 1758
悲哀的现实
悲哀的现实 2020-12-18 14:34

Even though there are multiple questions like this I can\'t get my query to return the row with the most recent date with a group by.

I have the following table..

5条回答
  •  独厮守ぢ
    2020-12-18 15:08

    To get most recent record for each from you can use a self join

    DB::table('message as m')
      ->select('m.*')
      ->leftJoin('message as m1', function ($join) {
            $join->on('m.from', '=', 'm1.from')
                 ->whereRaw(DB::raw('m.created_at < m1.created_at'));
       })
      ->whereNull('m1.from')
      ->orderBy('m.created_at', 'DESC')
      ->paginate(10);
    

    In SQL it will look like

    select m.*
    from message m
    left join message m1 on m.from = m1.from
    and m.created_at < m1.created_at
    where m1.from is null
    order by m.created_at desc
    

    Laravel Eloquent select all rows with max created_at

提交回复
热议问题