I have 2 models:
class Message extends Eloquent { public function conversation(){ return $this->belongsTo('Conversation', 'conversationId'); } public function sender(){ return $this->belongsTo('User', 'senderId')->select('id', 'userName'); } public function receiver(){ return $this->belongsTo('User', 'receiverId')->select('id', 'userName'); } } class DeskConversation extends Eloquent { }
I want to accept all the last messages of each conversation (those that are part of this array) ... in other words, I would like to take a few conversations and, for each of them, only the last message that was exchanged.
I can get all the messages for this entire conversation with this:
return Message::whereHas('conversation', function($query) use ($convIds) { $query->whereIn('id', $convIds); })->with('sender')->with('receiver')->orderBy('conversationId')->orderBy('id', 'DESC')->get();
where $convIds is an array of identifiers.
How to take only the last message for each conversation?
ps both models have timestamps.
source share