【问题标题】:Laravel: 1215 Cannot add foreign key constraint - when migratingLaravel:1215 无法添加外键约束 - 迁移时
【发布时间】:2019-07-31 09:36:48
【问题描述】:

我有一个表类别,它有自己的父类型。

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 类型。

【问题讨论】:

  • 为什么要创建引用您正在创建的同一个表的 FK? parent_id 应该在 parents 表上引用 id
  • 正如我在第一行提到的,类别有类别的父母
  • 哦,我的错。我没看到。

标签: php mysql laravel migration database-migration


【解决方案1】:

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

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

或

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

【讨论】:

    猜你喜欢
    • 2020-09-21
    • 2021-03-29
    • 2017-09-06
    • 2021-06-18
    • 2020-07-08
    • 2019-07-27
    • 2019-03-24
    • 2017-03-27
    • 1970-01-01
    相关资源
    最近更新 更多