laravel - Laravel:构建我自己的对话系统
问题描述
我尝试为我的应用程序构建简单的对话系统,但在规划该结构时遇到了一些麻烦。当用户转到“对话”页面时,它应该列出用户作为发送者或接收者的所有对话,并按最新消息排序。然后,当用户打开特定对话时,它应该列出来自该对话的所有消息。我计划了这样的事情:
创建对话表
$table->increments('id'); $table->integer('sender_id'); $table->integer('receiver_id'); $table->timestamps();
创建消息表
$table->increments('id'); $table->text('message'); $table->integer('conversation_id'); $table->integer('user_id'); $table->timestamps();
创建对话和消息模型
用户模型 - ?
public function conversations() { return $this->hasMany('App\Conversation', 'sender_id'); }
在这里我遇到了麻烦-我想与外键为“sender_id”或“receiver_id”的对话建立关系,并通过最新消息返回对话顺序。我怎样才能做到这一点?你能给我一些提示,当我返回用户时,如何解决用户、对话和消息之间的关系以返回所有信息?
我真的很感激任何帮助。
解决方案
首先,您应该使用如下消息定义对话关系:
对话模型
public function messages()
{
return $this->hasMany('App\Message');
}
您还应该定义反比关系:
消息模型
public function conversation()
{
return $this->belongsTo('App\Conversation');
}
您可以使用以下代码显示用户的所有对话:
public function getConversations($userId)
{
$conversations = Conversation::where('sender_id',$userId)->orWhere('receiver_id',$userId);
return view('yourview', compact('conversations'));
}
在您看来,您可以循环并找到每个对话中的每条消息:
@foreach($conversations as $conversation)
@foreach($conversation->messages as $message)
{{$message->message}}
@endforeach
@endforeach
在您的conversations
表格中,您可以有一个user_id
FK,您的关系也应如下所示:
用户模型
public function conversations()
{
return $this->hasMany('App\Conversation', 'user_id');
}
注意:您也可以使用receiver_id
orsender_id
作为外键。
通过这种关系,您可以从用户那里获得所有对话:
$user = User::find($id);
$user->conversations; // This will return all conversations from that user
您还可以使用Has Many Through关系从用户那里获取所有消息:
public function messages()
{
return $this->hasManyThrough('App\Message', 'App\Conversation');
}
另一种方法
users
另一种方法是在和之间创建一个数据透视表conversations
conversation_user
桌子_
id
user_id
conversation_id
这样,用户可以进行许多对话(多对多关系)。
您可以将messages
表更改为:
id
conversation_id
receiver_id
sender_id
content
...
您的消息模型
public function conversation()
{
return $this->belongsTo('App\Conversation', 'conversation_id');
}
用户模型
public function conversations()
{
return $this->belongsToMany('App\Conversation');
}
对话模型_
public function users()
{
return $this->belongsToMany('App\User');
}
public function messages()
{
return $this->hasMany('App\Message');
}
我认为这是最好的方法
如果您想获得对话和消息:
$user = User::find($id);
foreach($user->conversations as $conversation)
{
foreach($conversation->messages as $message)
{
echo $message->content;
}
}
另一种简单的方法是使用消息模型:
$userMessages = Message::where('receiver_id', $userId)->orWhere('sender_id',$userId)->get();
但是这样你只会得到消息,你可以找到对话:
foreach($userMessages->conversation as $conversation)
{
echo $conversation;
}
推荐阅读
- python - 将(冻结的)Tensorflow 模型加载到内存中时出错
- python - pandas:将数据框写入 excel 文件 *object*(不是文件)?
- ansible - Ansible,将字典合并到一次
- asp.net-core - EPPlus 是否支持 MS Office Equations?
- python - 如何将 csv 文件的行转换为对象列表?
- c# - Visual Studio Windows 应用程序 - 在标签中显示数字
- c - 为什么将函数作为函数的参数传递?
- regex - 星期几/月份范围内的较短正则表达式
- excel - Range.AdvancedFilter 产生不一致的结果
- reactjs - 以 NAME 为键将数据写入 Firebase