Jensseger Mongodb Laravel - 按嵌入文档的属性排序

时间:2018-05-06 13:07:36

标签: mongodb laravel jenssegers-mongodb

如何按子文档(从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 ...

1 个答案:

答案 0 :(得分:0)

将此关系添加到java -jar jenkins.war --httpPort="default"

Message::class

然后你应该可以通过

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