【问题标题】:Laravel get all conversations by the column user_id and every conversation should get all the messagesLaravel 通过 user_id 列获取所有对话,每个对话都应该获取所有消息
【发布时间】:2021-01-02 23:18:30
【问题描述】:

我有一张桌子 Conversations 有很多对话

我有消息表 消息表有很多消息 Messages 表包含一行,其中表中的每条消息都有一个行 conversation_id 这表明每条消息都属于一个对话

我可以使用

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

 /**
 * Get the Messages for the Conversation chat.
 */
public function messages()
{
    return $this->hasMany('App\Message');
}

在控制器中我能够获取属于该对话的所有消息 (1)

$messages = App\Conversation::find(1)->messages ;

我想要的是我想通过列 user_id 获取所有对话,并且每个对话都应该获取所有消息? 对话数组 如果可能的话是这样的

[
  //conversation 0 
  [ 
    [
      id: 1
      message : "Bla bla bla",     
    ],
    [
      id: 2
      message : "Response to Bla bla bla",     
    ],
    [
      id: 3
      message : "Bye",     
    ]  
  ],
  //conversation 1 
  [ 
    [
      id: 1
      message : "Bla bla bla",     
    ] 
  ],
    //conversation 2 
  [ 
    [
      id: 1
      message : "Bla bla bla",     
    ] 
  ],
]

请问我该怎么做,我不知道我应该使用什么

【问题讨论】:

    标签: laravel


    【解决方案1】:

    您可以获取用户的对话:

    $conversations = App\Conversation::with('messages')->where('user_id', $id)->get();
    

    $id 是用户 ID,with('messages') 返回会话消息集合。要访问它,您可以简单地执行以下操作:

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

    【讨论】:

    • 谢谢您,先生,如果您能提供链接,非常感谢您从文档中阅读此内容,再次感谢您
    • 这里是Click
    • 这里还有Eager Loading
    猜你喜欢
    • 2016-09-12
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 2016-03-24
    相关资源
    最近更新 更多