Get latest message (row) per user in Laravel

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

    I found this solution in another forum, I think that is what you were looking for. I post it so it can be useful for other users

            DB::select('
                SELECT t1.*
                FROM messages AS t1
                INNER JOIN
                (
                    SELECT
                        LEAST(sender_id, recipient_id) AS user_id,
                        GREATEST(sender_id, recipient_id) AS recipient_id,
                        MAX(id) AS max_id
                    FROM messages
                    GROUP BY
                        LEAST(sender_id, recipient_id),
                        GREATEST(sender_id, recipient_id)
                ) AS t2
                    ON LEAST(t1.sender_id, t1.recipient_id) = t2.sender_id AND
                       GREATEST(t1.sender_id, t1.recipient_id) = t2.recipient_id AND
                       t1.id = t2.max_id
                    WHERE t1.sender_id = ? OR t1.recipient_id = ?
                ', [auth()->guard('api')->user()->id, auth()->guard('api')->user()->id]);
    

    original post: https://laracasts.com/discuss/channels/laravel/get-the-latest-message-of-chat-model-with-mysql-just-cannot-get-the-idea-how-to-do-this?page=1#reply=392529

提交回复
热议问题