【问题标题】:How to create a private message system with Laravel如何使用 Laravel 创建私人消息系统
【发布时间】:2016-12-11 13:46:19
【问题描述】:

我正在实现没有任何包的简单私人消息应用程序。

消息表有以下列 id, from_id, to_id, message, created_at

我希望用户显示如下示例的消息-

用户1:嗨 用户2:你好

用户1:你好吗? 用户1:怎么了? 用户 2:很好。

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    这是many to many 关系。您应该在users 表中创建带有两个指向id 的键的数据透视表:

    Schema::create('messages_pivot', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('from_id')->unsigned();
        $table->integer('to_id')->unsigned();
        $table->string('message');
        $table->timestamps();
    });
    
    Schema::table('messages_pivot', function (Blueprint $table) {
        $table->foreign('from_id')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('to_id')->references('id')->on('users')->onDelete('cascade');
    });
    

    您可以使用relations 处理此数据透视表,也可以为其创建模型。

    【讨论】:

    • 不是很有用,而且只有 2 个用户的私人消息不一定需要多对多关系。
    • 如果看不懂,没必要投反对票。
    • 我从不反对任何人,但听起来它对其他人也不起作用。
    • @HassanAzimi 我不认为是你,昨天有人投了反对票。此外,这个解决方案对我也很有效。
    【解决方案2】:

    创建两个表ConversationsMessages在用户之间使用conversation_id(如果存在),然后在messages表中添加消息并使用user_id存储谁发送了消息。

    class CreateMessagesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('messages', function (Blueprint $table) {
                $table->increments('id');
                $table->text('message');
                $table->boolean('is_seen')->default(0);
                $table->boolean('deleted_from_sender')->default(0);
                $table->boolean('deleted_from_receiver')->default(0);
                $table->integer('user_id');
                $table->integer('conversation_id');
                $table->timestamps();
            });
        }
    
    
    class CreateConversationsTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('conversations', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('user_one');
                $table->integer('user_two');
                $table->boolean('status')->default(1);
                $table->timestamps();
            });
        }
    

    【讨论】:

      猜你喜欢
      • 2012-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-07
      • 2023-03-23
      • 2016-05-01
      • 2010-10-20
      • 2011-09-19
      相关资源
      最近更新 更多