Laravel migration fails with SQLSTATE[HY000]: General error: 1215

Laravel migration fails with SQLSTATE[HY000]: General error: 1215

我正在尝试使用 laravel 添加迁移。这是mi迁移文件。

public function up() {
    Schema::create('sl_categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title')->nullable();
        $table->integer('user_id')->unsigned()->nullable();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->softDeletes();
        $table->timestamps();
    });

    Schema::create('sl_images', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('image')->nullable();
        $table->integer('sl_category_id')->unsigned()->nullable();
        $table->integer('display_order')->nullable();
        $table->softDeletes();
        $table->timestamps();
    });

    Schema::table('sl_images', function(Blueprint $table) {
        $table->foreign('sl_category_id')->references('id')->on('sl_categories')->onDelete('cascade');
    });
}

public function down() {
    Schema::dropIfExists('sl_images');
    Schema::dropIfExists('sl_categories');
}

但不幸的是我遇到了这个错误。

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table sl_images add constraint sl_images_sl_category_id_foreign foreign key (sl_category_id) references sl_categories (id) on delete cascade)

终于找到答案了。问题是 InnoDB 不允许在列引用不匹配的列类型时创建外键约束。如果简单的说,

这是一个大整数

$table->bigIncrements('id'); 

这是一个简单的整数。,

 $table->integer('sl_category_id')->unsigned()->nullable();

所以我们要把后面那行改成bigInteger,

$table->bigInteger('sl_category_id')->unsigned()->nullable();

我添加这个答案以防其他人发现它的一些用途。