SQLSTATE[HY000]:一般错误:1215 无法添加外键约束 laravel 9
尝试分配外键,但是当您运行迁移时,我收到此错误,我不明白问题是什么。
SQLSTATE[HY000]:一般错误:1215 无法添加外键约束(SQL:alter table
categories
添加约束categories_parent_key_foreign
外键(parent_key
) 在删除级联上引用categories
(key
)
$table->bigIncrements('id');
$table->string('key', 64)->unique();
$table->string('parent_key', 64)->nullable()->index();
$table->string('title', 256)->index()->unique();
$table->foreign('parent_key')->references('key')
->on((new Category())->getConnection()->getDatabaseName() . '.' . Category::TABLE)
->onDelete('cascade');
Trying to assign foreign key but when you run migrate, I get this this error, I do not understand what the problem is.
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
categories
add constraintcategories_parent_key_foreign
foreign key (parent_key
) referencescategories
(key
) on delete cascade)
$table->bigIncrements('id');
$table->string('key', 64)->unique();
$table->string('parent_key', 64)->nullable()->index();
$table->string('title', 256)->index()->unique();
$table->foreign('parent_key')->references('key')
->on((new Category())->getConnection()->getDatabaseName() . '.' . Category::TABLE)
->onDelete('cascade');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我也有同样的问题。
当模型与其自身存在关系(自关系)时,就会出现问题。
要解决这个问题,首先必须创建迁移文件,然后必须在另一个迁移文件中分配外键。
您必须从迁移文件中删除外键分配,然后创建新的迁移文件,然后添加关系语句来分配外键。 (迁移文件的顺序很重要)。
create_category_table
create_category_relation_table
然后
php artisan 迁移
I had the same problem.
The problem arises when a model has a relationship with itself (self-relation).
To solve this problem, first, the migration file must be created and then the foreign key must be assigned in another migration file.
You must remove the foreign key assignment from the migration file and create the new migration file after that, then add relations statements to assign a foreign key. (the order of the migration files is important).
create_category_table
create_category_relation_table
And then
php artisan migration
就我而言,问题在于引用的表键和键引用的不同数据类型。例如,整数(无符号) 与 bigInteger(无符号)。
In my case the problem was in the different datatypes of the referenced table key and the key reference. For instance, integer(unsigned) vs bigInteger(unsigned).