简体   繁体   English

Laravel 4-如何在一个查询中获取每条记录的最新with()

[英]Laravel 4 - How to get the latest in with() for each record in one query

I'm working on a messaging system in laravel 4. I have the following tables users, conversations, conversation_user(pivot) and messages. 我正在laravel 4中使用消息传递系统。我有下表表格表user,conversation,conversation_user(pivot)和消息。 users and converations have many to many relationship, conversations have many messages and users have many messages. 用户和对话具有多对多关系,对话有许多消息,而用户有许多消息。 I get the conversations of a user like so:¨ 我得到了这样的用户对话:

$usersConversations = Auth::user()->conversations;

Then I loop over them to get their ids to be able to select only those messages users and messages like so: 然后,我遍历它们以获取其ID,以便仅选择那些消息用户和消息,如下所示:

if(0 < $usersConversations->count()) {
    foreach ($usersConversations as $conversation) {
        $conversationIds[] = $conversation->id;
    }
    $conversations = Conversation::with('users', 'messages')->whereIn('id', $conversationIds)->get();
} else {
    $conversations = false;
}

but this returns all users and all messages for each of the conversations. 但这会返回所有用户和每个对话的所有消息。 I wan't all the users but only the latest message for each conversation. 我不需要所有用户,但每次对话只需要最新消息。 So I tried doing this instead: 所以我尝试这样做:

$conversations = Conversation::with('users', 'latestMessage')->whereIn('id', $conversationIds)->get(); 

// and have this in my Conversation model
public function latestMessage() {
    return $this->hasMany('Message')->orderBy('created_at', 'desc')->take(1);
}

This does get me the latest message, but only the very latest, and only one, no matter how many convesations there are. 这确实给了我最新的消息,但无论有多少次奉献,都只有最新的消息,只有一个。 I wan't one message for each of the conversations. 我不会在每次对话中都留言。

Can anyone help me with how to construct that query? 谁能帮助我构造该查询? Thanks in advance. 提前致谢。

Here is what you are looking for. 这是您要找的东西。

$conversations = Conversation::with(array('users', 'messages' => function($query){
    $query->orderBy('created_at', 'desc')
        ->take(1);
})->get();

There is no need to use the latestMessage function. 无需使用latestMessage函数。

EDIT : The item returned will be a collection if the relationship is not a 1-1. 编辑 :如果关系不是1-1,则返回的项目将是一个集合。 Even if you use first() instead of take(1) . 即使您使用first()代替take(1) Honestly I think it's not intended, but to work around this, make sure to output your messages as such: 老实说,我认为这不是故意的,但要解决此问题,请确保将您的消息输出为:

foreach($conversations as $conversation){
    echo $conversation->messages->first()->YOUR_FIELD;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM