我想按照使用 Jenssegers 和 Mongodb 插入的顺序,根据 created_at 时间从数据库中获取最后 2 个插入的用户聊天。我尝试了一些查询,但无法获得所需的结果。
这些查询按插入顺序给出了前两个聊天:
$prev_chats = ChatMessages::where('chat_id','=', $chat_id)->take(2)->get();
$prev_chats = ChatMessages::orderBy('created_at','asc')->where('chat_id','=', $chat_id)->take(2)->get();
$prev_chats = ChatMessages::orderBy('created_at','asc')->where('chat_id','=', $chat_id)->paginate(2);
当我尝试颠倒顺序时,它会获取最后 2 个,但插入它们的序列会发生变化(意味着最后一个变为第一个)。
$prev_chats = ChatMessages::orderBy('created_at','desc')->where('chat_id','=', $chat_id)->paginate(2);
$prev_chats = ChatMessages::orderBy('created_at','desc')->where('chat_id','=', $chat_id)->take(2)->get();
有没有办法按插入的顺序获取最后 2 条记录。或者可以有另一个逻辑来做到这一点。
收集中的样本数据:
{
"_id": ObjectId("56fd1ad11c8cb633208b4569"),
"message": "I deal in Cosmetic Products.",
"type": "groupchat",
"from_id": "56b07a5a083f119a0b8b4569",
"chat_id"▼: "56fa3f5f1c8cb667138b4567",
"updated_at": ISODate("2016-03-31T12:40:49.807Z"),
"created_at": ISODate("2016-03-31T12:40:49.807Z")
}
{
"_id": ObjectId("56fd1ab41c8cb6f1298b456a"),
"message": "What business do you deal in.",
"type": "groupchat",
"from_id": "56b087d4083f11ea218b4567",
"chat_id": "56fa3f5f1c8cb667138b4567",
"updated_at": ISODate("2016-03-31T12:40:20.465Z"),
"created_at": ISODate("2016-03-31T12:40:20.465Z")
}