首页 > 解决方案 > Laravel 6 on Migration: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

问题描述

我试图在我的桌子上进行迁移,但是当我进行 laravel 迁移时,出现了一个错误。

SQLSTATE [HY000]:一般错误:1215 无法添加外键约束(SQL:alter table subscribersadd constraint subscribers_user_id_foreignforeign key ( user_id) references users( id) on delete set null)

这是我要迁移的表:

Schema::create('subscribers', function (Blueprint $table) {
            $table->increments('id');
            $table->string('account_no');
            $table->enum('type',['individual','company'])->default('individual');
            $table->string('title')->nullable();
            $table->string('firstname');
            $table->string('middlename');
            $table->string('lastname');
            $table->string('suffix')->nullable();
            $table->enum('gender',['male','female']);
            $table->date('birthday')->nullable();
            $table->string('contact_no');
            $table->string('email');
            $table->tinyInteger('status')->default(1);
            $table->integer('user_id')->unsigned();
            $table->unsignedInteger('created_by');
            $table->unsignedInteger('updated_by');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('set null');
            $table->foreign('created_by')->references('id')->on('users')->onDelete('set null');
            $table->foreign('updated_by')->references('id')->on('users')->onDelete('set null');
        });

标签: mysqllaravel

解决方案


现在试试

改变这个

$table->unsignedBigInteger('user_id');
Schema::create('subscribers', function (Blueprint $table) {
            $table->increments('id');
            $table->string('account_no');
            $table->enum('type',['individual','company'])->default('individual');
            $table->string('title')->nullable();
            $table->string('firstname');
            $table->string('middlename');
            $table->string('lastname');
            $table->string('suffix')->nullable();
            $table->enum('gender',['male','female']);
            $table->date('birthday')->nullable();
            $table->string('contact_no');
            $table->string('email');
            $table->tinyInteger('status')->default(1);
            $table->unsignedBigInteger('user_id');
            $table->unsignedInteger('created_by');
            $table->unsignedInteger('updated_by');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('set null');
            $table->foreign('created_by')->references('id')->on('users')->onDelete('set null');
            $table->foreign('updated_by')->references('id')->on('users')->onDelete('set null');
        });

推荐阅读