常规错误1215:无法添加外键约束

5lhxktic  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(467)

我得到以下错误:
sqlstate[hy000]:常规错误:1215无法添加外键约束(sql:alter table) subtags 添加约束 subtags_tag_id_foreign 外键( tag_id )参考文献 id ( tags )删除时(级联)
在查看了有关stackoverflow和此blogpost上此错误的其他答案之后:https://www.percona.com/blog/2017/04/06/dealing-mysql-error-code-1215-cannot-add-foreign-key-constraint/ 我还是不明白为什么我会出错。
这是subtag表的迁移:

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();
    });
}
eivgtgni

eivgtgni1#

您可以在迁移之前禁用检查外来密钥

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

ecr0jaav2#

查询显示您将列表放错了位置(&T):

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

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

参考应为“表”上的“列”,如:

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

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

相关问题