如何获取最近的对话 Laravel

How to get recent conversations Laravel

我已经可以使用以下 SQL 命令执行此操作

SELECT * FROM users AS u INNER JOIN messages AS m ON u.ID IN (m.senderID, m.recipientID) WHERE u.ID <> $userID GROUP BY u.ID ORDER BY m.created_at DESC

如何将其转换为 Laravel 查询生成器,我有消息模型和用户模型

这样做:

$users  = User::join('messages', 'users.ID', '=', 'messages.user_id')
            ->whereIn('users.ID',['messages.senderId', 'messages.recipientID'])
            ->where('users.ID', '!=', $userID)
            ->groupBy('users.ID')
            ->orderBy('created_at','DESC')
            ->get();