【发布时间】:2019-05-10 12:29:29
【问题描述】:
我有一个 Conversation 模型,其中包含许多 ConversationMessage 模型。
现在我想根据对话的最后一条消息对对话进行排序。基本上就像WhatsApp。如何构建查询?
作为我的代码的旁注:对话包含一个用户 (user_id)
和一家关联公司 (company_id)。公司与用户有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();
对ConversationMessage 关系模型进行排序,而不是对话。如何根据最后一条消息对Conversations 进行排序?
【问题讨论】:
-
在任何事情之前,我不确定,但我认为您可以在一行中写下您的第一个
whereHas:Conversation::whereHas('company.users', function ($q) use ($userId) { $q->where('users.id', $userId); }) -
没错,谢谢!