我收到以下错误:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
subtags
add constraintsubtags_tag_id_foreign
foreign key (tag_id
) referencesid
(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/