database - 如何区分聊天应用 Laravel 中的发送者和接收者?
问题描述
我正在 Laravel 5.7 中制作一个私人(一对一)聊天应用程序。我认为问题出在架构上。如果user1已登录并且他与user2创建了一个新对话。这将使用conversation_id=1创建。下次当user2登录时,假设他将在发件人列中找到他的ID,但他不会找到他的ID,将创建不应创建的新对话,因为要创建新对话,我们必须检查在发送方和接收方列中。
这是我的架构
=======User Table========
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
=============Chat Table=============
Schema::create('chats', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user1_id')->nullable();
$table->foreign('user1_id')->references('id')->on('users');
$table->unsignedInteger('user2_id')->nullable();
$table->foreign('user2_id')->references('id')->on('users');
$table->timestamps();
});
===============Messages Table================
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('chat_id')->nullable();
$table->foreign('chat_id')->references('id')->on('chats');
$table->text('messages');
$table->timestamps();
});
或许你就这样理解了。
Users Chats
id name chat_id user1_id user2_id
1 Mark 1 1 2
2 David 2 2 1
3 Henzard 3 2 3
4 3 2
请建议我一个更好的解决方案。
解决方案
我可能忽略了架构的一个或多个复杂性,但我想出了以下内容。
用户- 保留您现有的用户表。
对话- 这将代表单个对话、发起用户和对话开始的日期。
- id
- user_id # user who initiated conversation
- created_at
conversation_user - 这将代表作为对话一部分的每个用户。虽然您的要求表明每个对话都是在两个用户之间进行的,但这种结构也允许您在未来进行群组对话 - 如果需要的话。
或者,您可以添加read_at
时间戳来存储用户上次阅读对话的日期/时间。这可以用来推断用户在对话中是否有未读消息。
- id
- conversation_id
- user_id
- read_at # when user last read conversation
- created_at
消息- 这将代表对话中的一条消息。只需要记录发送用户,因为可以阅读消息的用户是由conversation_user
表决定的。
- id
- conversation_id
- user_id # user who sent message
- message
- created_at
- updated_at
推荐阅读
- mysql - 计算从内容构建到内容构建过程中丢失和获得的记录
- oracle - 在弹出警报中而不是在状态栏上显示错误消息
- php - 带有 PHP 的 Google Drive API - 刷新令牌获取消息“刷新令牌必须传入或设置为 setAccessToken 的一部分”的问题
- ruby-on-rails - 尝试使用 Capistrano 部署 Rails 应用程序来做 Droplet
- angularjs - AngularJS 控制器调用 MVC 控制器 - 它成功但启动了一个包含 null 的错误
- git - Git-tfs:获取笔记
- java - 如何检查页面中是否存在弹出窗口?
- haskell - 通过堆栈安装 bhoogle
- r - 从 R 中的线性模型列表中映射 emmeans
- javascript - 如何从另一个任务运行器执行/捆绑 JS 与 Webpack?