Get latest message (row) per user in Laravel

后端 未结 9 1086
逝去的感伤
逝去的感伤 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 01:51

    I like a simpler approach which is mentioned here.

    In your User model additionally to existing messages() relationship, add this relationship

    public function latestMessage() 
    {
        return $this->hasOne(Message::class, 'recipient_id')->latest();
    }
    

    Then when you query simply query like this.

    $messages = User::with('latestMessage')->get();
    

    $messages contains latest message per user.

    Edit

    In order to order the result by datetime/id you could do it like this.

    $messages = User::with(['latestMessage' => function($message) {
        $message->orderBy('id', 'desc');
    }])->get();
    

    $messages contains latest message per user ordered by id. Refer this answer

提交回复
热议问题