Get latest message (row) per user in Laravel

后端 未结 9 1120
逝去的感伤
逝去的感伤 2021-02-19 01:37

TL;DR: Need latest message from each sender.

In my Laravel application I have two tables:

Users:

  • id
  • name

Messages:

9条回答
  •  再見小時候
    2021-02-19 02:03

    Taking inspiration from this post, the most efficient way to do this would be like so:

    DB::table('messages AS m1')
        ->leftjoin('messages AS m2', function($join) {
            $join->on('m1.sender_id', '=', 'm2.sender_id');
            $join->on('m1.id', '<', 'm2.id')
        })->whereNull('m2.id')
        ->select('m1.sender_id', 'm1.body', 'm1.created_at')
        ->orderBy('m1.created_at', 'm1.desc')->get();
    

    While it is not the most Laravel friendly, it is the best solution based on performance as highlighted by the post linked in this answer above

提交回复
热议问题