Вы можете добавить поле timestamp
, например last_message_at
, к вашей модели Conversations
, и когда новое сообщение будет добавлено к этому Conversation
, обновите это поле, а затем вы сможете отсортировать результат на основе last_message_at
.
Или вы можете отфильтровать результаты в запросе, как показано ниже (проверьте, работает ли он):
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();