php - 一般错误 1215 : cannot add foreign key constraint

标签 php mysql database laravel laravel-5.6

我收到以下错误:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table subtags add constraint subtags_tag_id_foreign foreign key (tag_id) references id (tags) on delete cascade)

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

最佳答案

您的查询显示您已将列和表放错位置:

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'));
});

关于php - 一般错误 1215 : cannot add foreign key constraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50775308/

相关文章:

php - 如何从mysql数据库中查询两张表的数据并显示一张HTML表

php - 数组到字符串到数组的转换

mysql - #1054 - 't2.id_pro' 中的未知列 'where clause'

php - 如何使用 jquery、ajax 和 codeigniter 创建 Like 按钮

Mysql时间戳默认值

python - 如何使用python将DataFrame中的列插入到具有可变列数的数据库表的新列中

database - 如何存储从网站抓取的数据

PHP - 如何更新 txt 文件中的 JSON 数据?

php - 使用 fgetcsv 解析未转义的双引号

php - 使用 PHP 从只读 Google 表格获取数据