[英]How to make a foreign key within two columns is the same table?
I have a database called laravelpro
and in it there is a table called categories
.我有一个名为laravelpro
的数据库,其中有一个名为categories
的表。 Here is the migration that makes the categories
table.这是制作categories
表的迁移。
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->unsignedBigInteger('parent')->default(0);
$table->foreign('parent')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
In categories
table, a category can be another category's parent(I'm doing this with the parent
field).在categories
表中,一个类别可以是另一个类别的父级(我在parent
级字段中这样做)。 As you can see there is a line in migration that is making a foreign key from the parent
field to the id
field.如您所见,迁移中有一行正在创建从parent
字段到id
字段的外键。 The purpose of doing this action is that I want to remove all subcategories of a category after I remove the parent category and so on... I ran the migration with no errors but when I want to add a category, I will face his error:做这个动作的目的是我想在删除父类别等之后删除一个类别的所有子类别......我运行迁移没有错误但是当我想添加一个类别时,我会遇到他的错误:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
(`laravelpro`.`categories`, CONSTRAINT `categories_parent_foreign` FOREIGN KEY (`parent`) REFERENCES `categories` (`id`) ON DELETE CASCADE)
INSERT INTO `categories` (`name`, `parent`, `updated_at`, `created_at`) VALUES (test, 0, 2022-10-06 20:33:41, 2022-10-06 20:33:41)
I searched a lot and didn't find anything related to my subject.我搜索了很多,但没有找到与我的主题相关的任何内容。 Any help would be appreciated...任何帮助,将不胜感激...
Make parent nullable.使父级可为空。
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->unsignedBigInteger('parent')->nullable();
$table->foreign('parent')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.