0

如何按子文档上的属性排序(从 belongsTo 关系延迟加载)?

我有:

Message::with(['conversation'])
->where(.....)
->get()

这将返回:

[
{
       "_id": "5aee075893782d1b1f460b13",
        ......
        "updated_at": "2018-05-05 19:34:48",
        "created_at": "2018-05-05 19:34:48",
  "conversation": {
            "_id": "5aee075793782d1b1f460b12",
            "updated_at": "2018-05-06 12:21:23",
            "created_at": "2018-05-05 19:34:47",
            "messageCount": 5
        }
}
]

我现在需要在对话中通过 updated_at 订购(消息)。我试过 ->orderBy('conversation.updated_at','desc'),但没有运气。我猜问题是由于延迟加载,对话对象不可用于 orderBy ......

4

1 回答 1

0

将此关系添加到Message::class

public function conversationLatestFirst(): HasMany
{
    return $this->hasMany(Conversation::class)->orderByDesc('created_at');
}

然后您应该可以通过以下方式查询

Message::with(['conversationLatestFirst'])
->where(.....)
->get()
于 2018-05-06T14:49:57.280 回答