Get latest message (row) per user in Laravel

后端 未结 9 2525
感动是毒
感动是毒 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:47

    this may be a solution (not tested though)

    User::with([
    'messages' => function ($q) {
        $q->select('sender_id', 'body')->groupBy('sender_id')->orderBy('created_at', 'desc');
    }
    ])->find(1);
    

提交回复
热议问题