ciccioassenza
ciccioassenza

Reputation: 233

get max value for each related model with eloquent in laravel

I have 2 model:

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 {

}

What I want is to take all the last messages of each conversation (those included in a given array)... in other words I would like to take some conversations and, for each of them, only the last message that was exchanged.

I'm able to get all the messages for all the given 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 ids.

How to take, for each conversation, only the last message?

p.s. both models have timestamps fields.

Upvotes: 0

Views: 4163

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81167

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;

Upvotes: 4

Related Questions