get max value for each related model with eloquent in laravel

佐手、 提交于 2020-01-07 06:25:28

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/25655388/get-max-value-for-each-related-model-with-eloquent-in-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!