获得每个相关模型的最大值与雄辩的Laravel [英] get max value for each related model with eloquent in laravel

查看:267
本文介绍了获得每个相关模型的最大值与雄辩的Laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个模型:

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

其中 $ convIds 是一组ids

每个会话中只有最后一条消息如何?

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

推荐答案

这是您需要的:

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

然后只是:

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

这篇关于获得每个相关模型的最大值与雄辩的Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆