使用外键删除多个表中的条目
以下设置将:
- 允许我删除现有条目
- 阻止我在
products
中创建新条目
这可能是因为之前在 products
中创建了条目categories_products
。但在知道产品 ID 之前,我无法在 categories_products
中创建条目。
你会怎么办?
ALTER TABLE products
ADD CONSTRAINT FK_products
FOREIGN KEY (id) REFERENCES categories_products(product_id)
ON UPDATE CASCADE
ON DELETE CASCADE;
表格
categories:
id, name
categories_products:
category_id, product_id
products:
id, name
创建每个条目的顺序
- 在类别中创建条目
- 在产品中创建条目
- 使用 1. 和 2. 中的 ID 创建
类别之间的关系< /code> 和
产品
The following setup will:
- Allow me to delete existing entries
- Prevent me from creating new entries in
products
This probably happens because entries gets created in products
before categories_products
. But I cannot create entries in categories_products
before I know the product ID.
What would you do?
ALTER TABLE products
ADD CONSTRAINT FK_products
FOREIGN KEY (id) REFERENCES categories_products(product_id)
ON UPDATE CASCADE
ON DELETE CASCADE;
Tables
categories:
id, name
categories_products:
category_id, product_id
products:
id, name
Which order each entry gets created
- Create an entry in categories
- Create an entry in product
- Using the IDs from 1. and 2. to create a relationship between
categories
andproducts
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你的约束是倒退的。该外键应该位于
categories_products
表中并引用products
表,而不是相反:I think you have your constraint backwards. That foreign key should be on the
categories_products
table and referencing theproducts
table, not the other way around:您有一个多对多关系:
因此,您应该添加两个外键来支持这种类型的关系。这些外来必须添加到categories_products表中:
然后,要删除类别和相关产品,请使用如下查询:
您还可能需要添加ON DELETE CASCADE子句,它将帮助您从父表中删除行并自动删除子表中的匹配行。例如,下一个查询将自动删除
categories_products
表中的相关记录:You have a many-to-many relation:
So, you should add two foreing keys to support this type of relation. These foreign have to be added to the categories_products table:
Then, to delete category and related products use a query like this:
You also may want to add ON DELETE CASCADE clause, it will help you to delete the row from the parent table and automatically delete the matching rows in the child table. For example, next query will remove automatically related records in
categories_products
table: