Get latest message (row) per user in Laravel

后端 未结 9 1085
逝去的感伤
逝去的感伤 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:05

    This is the most "Eloquent way" I have found of doing this:

    In User model:

    public function messages() {
        return $this->hasMany(Message::class, 'recipient_id');
    }
    
    public function latestMessagePerSender()
    {
        return $this->messages()
            ->whereNotExists(function ($query) {
                $query->from('messages AS m2')
                    ->whereRaw('m2.sender_id = messages.sender_id')
                    ->whereRaw('m2.created_at > messages.created_at');
        });
    }
    

    Then just $user->latestMessagePerSender

提交回复
热议问题