简体   繁体   English

Laravel按最新消息对对话进行排序

[英]Laravel sort conversations by last message

I have a Conversation model that has many ConversationMessage models. 我有一个Conversation ,有许多模型ConversationMessage车型。

Now I want to sort the conversations based on the last message of the conversation. 现在,我想根据对话的最后一条消息对对话进行排序。 Basically like WhatsApp. 基本上就像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 ). 作为我的代码的补充说明:对话包含一个用户( user_id )和一个关联的公司( company_id )。 Company has a belongsToMany relation to user. 公司与用户有一个belongsToMany关系。

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. 这样对ConversationMessage关系模型进行排序,而不对对话进行排序。 How can I sort the Conversations based on the last message? 如何根据上一条消息对Conversations排序?

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 . 您可以将诸如last_message_at类的timestamp字段添加到您的“ Conversations模型中,并且当向该“ Conversation添加Conversation更新该字段,然后您可以根据last_message_at对结果进行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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM