1

I want to fetch last 2 inserted chats of users according to the created_at time from the database in the sequence they were inserted using Jenssegers and Mongodb. I have tried some queries but not able to get the desired result.

These queries gives the first two chats in the sequence they were inserted:

$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);

When I try to reverse the order then it fetch the last 2 but the serial in which they were inserted changes(Means Last becomes First).

$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();

Is there a way to get the last 2 records in the sequence they were inserted. Or there can be a another logic to do this.

Sample data in collection:

{
   "_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") 
}
Mukesh Joshi
  • 2,784
  • 4
  • 24
  • 34

0 Answers0