Laravel sort conversations by last message

不打扰是莪最后的温柔 提交于 2021-01-28 09:23:41

问题


I have a Conversation model that has many ConversationMessage models.

Now I want to sort the conversations based on the last message of the conversation. Basically like WhatsApp. How do I build the query?

As a sidenote to my code: Conversation contains a user (user_id) and a company associated (company_id). Company has a belongsToMany relation to user.

Conversation::whereHas('company', function ($q) use ($userId) {
    $q->whereHas('users', function ($q1) use ($userId) {
        $q1->where('users.id', $userId);
    });
})->orWhereHas('user', function($q) use ($userId) {
    $q->where('user.id', $userId);
})->with(array('conversationMessage' => function($q) {
    $q->orderBy('created_at', 'DESC');
})->get();

That sort the ConversationMessage relation models but not the conversations. How can I sort the Conversations based on the last message?


回答1:


You can add a timestamp field like last_message_at to your Conversations model and when a new message is added to that Conversation update that field, then later you can sort the result based on last_message_at.

Or you can filter results in the query like below(Test it see if it works):

    Conversation::whereHas('company', function ($q) use ($userId) {
        $q->whereHas('users', function ($q1) use ($userId) {
            $q1->where('users.id', $userId);
        });
    })->orWhereHas('user', function($q) use ($userId) {
        $q->where('user.id', $userId);
    })->with(array('conversationMessage' => function($q) {
        $q->orderBy('created_at', 'DESC');
    })
    ->selectRaw("conversations.*, (SELECT MAX(created_at) from conversation_messages WHERE conversation_messages.conversation_id=conversations.id) as latest_message_on")
    ->orderBy("latest_message_on", "DESC")
    ->get();


来源:https://stackoverflow.com/questions/53691561/laravel-sort-conversations-by-last-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!