Get maximum value for each related model with eloquent in laravel

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.

0
source share
1 answer

This is what you need:

 /** * Conversation has one latest Message * * @return Illuminate\Database\Eloquent\Relations\HasOne */ public function latestMessage() { return $this->hasOne('Message')->latest(); } 

Then just:

 $conversations = Conversation::with('latestMessage')->get(); // then each latest message can be accessed: $conversation->latestMessage; $conversations->first()->latestMessage; 
+2
source

Source: https://habr.com/ru/post/1206037/


All Articles