Laravel:1215无法添加外键约束-迁移时

时间:2019-03-09 15:09:31

标签: php mysql laravel migration database-migration

我的表类别具有其自身类型的父项。

Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->integer('parent_id')->unsigned()->nullable()->default(null);
        $table->foreign('parent_id')->references('id')->on('categories');
        $table->timestamps();
    });

投掷:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `categories` add constraint `categories_parent_id_foreign` foreign key (`parent_id`) references `categories` (`id`))

我已经尝试过在单独的Schema :: table函数中将parent_id设置为外部,但没有成功。表是InnoDB类型。

1 个答案:

答案 0 :(得分:2)

尝试将FK从整数更改为bigInteger:

$table->bigInteger('parent_id')->unsigned()->nullable()->default(null);

$table->unsignedBigInteger('parent_id')->nullable()->default(null);