Get latest message (row) per user in Laravel

后端 未结 9 2501
感动是毒
感动是毒 2021-02-19 01:04

TL;DR: Need latest message from each sender.

In my Laravel application I have two tables:

Users:

  • id
  • name

Messages:

9条回答
  •  爱一瞬间的悲伤
    2021-02-19 01:42

    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

提交回复
热议问题