debugging 如何通过laravel迁移根据外键链接两个表

b91juud3  于 2022-11-24  发布在  其他
关注(0)|答案(2)|浏览(104)

我尝试将thread表链接到message表,但在迁移时,我收到一条错误消息:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `thread` add constraint `thread_id_foreign` foreign key (`id`) references `message` (`thread_id`))

我做错了什么?我如何才能做到这一点?
用户迁移:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('email')->unique();
        $table->string('full_name');
        $table->string('password');
        $table->string('bio');
        $table->rememberToken();
        $table->timestamps();
    });
}

下面是线程迁移:

Schema::create('thread', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->foreign('id')
            ->references('thread_id')
            ->on('message');
    });

以下是邮件迁移:

Schema::create('message', function (Blueprint $table) {
        $table->id();
        $table->unsignedInteger('user_id');
        $table->unsignedInteger('thread_id');
        $table->string('body');
        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
    });
mhd8tkvw

mhd8tkvw1#

您需要使用unsignedBigInteger作为外键列的
并且应该为子表而不是父表设置外键
试试看:

Schema::create('thread', function (Blueprint $table) {
        $table->id();
        $table->string('title');
    });
Schema::create('message', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('user_id');
        $table->unsignedBigInteger('thread_id');
        $table->string('body');

        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');

        $table->foreign('thread_id')
            ->references('id')
            ->on('thread')
            ->onDelete('cascade');
    });
bvpmtnay

bvpmtnay2#

如果要将线索表链接到消息,请按如下方式使用
注意:请确保先创建消息迁移,然后再创建线程迁移

Schema::create('message', function (Blueprint $table) {
        $table->id();
        // $table->unsignedInteger('thread_id');-> No Need for this column in here
        $table->string('body');
        $table->foreignId('user_id')->constrained('users')->onDelete('cascade');
    });

   Schema::create('thread', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->foreignId('message_id')->constrained('message')->onDelete('cascade');
    });

但如果您希望将消息表链接到线程表,则可以这样使用它

Schema::create('thread', function (Blueprint $table) {
        $table->id();
        $table->string('title');
    });

    Schema::create('message', function (Blueprint $table) {
        $table->id();
        $table->foreignId('thread_id')->constrained('thread')->onDelete('cascade');
        $table->string('body');
        $table->foreignId('user_id')->constrained('users')->onDelete('cascade');
    });

相关问题