首页 > 解决方案 > 如何区分聊天应用 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

请建议我一个更好的解决方案。

标签: databaselaravel-5eloquentchat

解决方案


我可能忽略了架构的一个或多个复杂性,但我想出了以下内容。

用户- 保留您现有的用户表。

对话- 这将代表单个对话、发起用户和对话开始的日期。

- 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

推荐阅读