【问题标题】:General error 1215: cannot add foreign key constraint一般错误 1215:无法添加外键约束
【发布时间】:2018-06-09 14:29:53
【问题描述】:

我收到以下错误:

SQLSTATE[HY000]:一般错误:1215 无法添加外键约束(SQL:更改表subtags 添加约束subtags_tag_id_foreign 外键(tag_id)在删除级联时引用id(tags))

在查看有关 stackoverflow 上的此错误的其他答案和此博文:https://www.percona.com/blog/2017/04/06/dealing-mysql-error-code-1215-cannot-add-foreign-key-constraint/ 后,我仍然无法弄清楚为什么会出现错误。

这是子标签表的迁移:

public function up()
{
    Schema::create('subtags', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->integer('tag_id')->unsigned();
        $table->integer('id')->unsigned();
        $table->string('name');
        $table->timestamps();
    });

    Schema::table('subtags', function (Blueprint $table) {
        $table->foreign('tag_id')
            ->references('tags')
            ->on('id')
            ->onDelete('cascade');

        $table->primary(array('tag_id', 'id'));
    });
}

在出现错误时,标签表已经创建,我找不到任何错别字,但只是为了确保,这里是标签表迁移:

public function up()
{
    Schema::create('tags', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

【问题讨论】:

  • 尝试同时指定onUpdate('cascade')
  • 看查询,好像外表和列倒过来了,应该是->on('tags')->references('id')
  • @NiettheDarkAbsol 是的,有问题....好吧,这是我生命中的一个美好时光,浪费了 xD。非常感谢!
  • 很遗憾听到您浪费了生命中的一个小时。下次,您可以通过阅读以下文档将浪费的时间减少到 5 分钟:laravel.com/docs/5.6/migrations#foreign-key-constraints

标签: php mysql database laravel laravel-5.6


【解决方案1】:

您的查询表明您在以下位置放错了列和表:

Schema::table('subtags', function (Blueprint $table) {
    $table->foreign('tag_id')
          ->references('tags')
          ->on('id')
          ->onDelete('cascade');

    $table->primary(array('tag_id', 'id'));
});

Reference 应该是 "column" on "Table" 比如:

Schema::table('subtags', function (Blueprint $table) {
    $table->foreign(id'tag_id')
          ->references('id')
          ->on('tags')
          ->onDelete('cascade');

    $table->primary(array('tag_id', 'id'));
});

【讨论】:

    【解决方案2】:

    您可以在迁移前禁用检查外键

    DB::statement('SET FOREIGN_KEY_CHECKS=0;');
    ...
    DB::statement('SET FOREIGN_KEY_CHECKS=1;');
    

    【讨论】:

      猜你喜欢
      • 2020-06-12
      • 2019-12-27
      • 2021-03-31
      • 2019-09-08
      • 2021-03-29
      • 2019-03-02
      • 2018-07-29
      • 2018-07-29
      • 2020-03-25
      相关资源
      最近更新 更多