一般错误1215:无法添加外键约束

时间:2018-06-09 14:29:54

标签: php mysql database laravel laravel-5.6

我收到以下错误:

  

SQLSTATE [HY000]:常规错误:1215无法添加外键约束(SQL:alter table 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();
    });
}

2 个答案:

答案 0 :(得分:1)

您的查询显示您错放了列&表格:

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

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

参考应为" " on " "像:

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

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

答案 1 :(得分:0)

您可以在迁移前禁用check foreigns键

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