[英]Foreign keys and constraints on pivot tables, on delete cascade
I have designed my database structure, like below to support the creation of multiple shops and users assigned to those shops. 我设计了我的数据库结构,如下所示,支持创建多个商店和分配到这些商店的用户。 My tables use InnoDB storage engine.
我的表使用InnoDB存储引擎。
[user]
user_id
[user_profile]
user_profile_id
user_id
[user_to_shop] PIVOT
user_id
shop_id
[shop]
shop_id
[shop_profile]
shop_profile_id
shop_id
[category_to_shop] PIVOT
category_id
shop_id
[category]
category_id
[category_description]
category_description_id
category_id
[product_to_category] PIVOT
product_id
category_id
[product_to_shop] PIVOT
product_id
shop_id
[product]
product_id
...
...
What I want to achieve is to delete all related records(category records, shop records, ..., ...) when a user(user_id) is deleted. 我想要实现的是删除用户(user_id)时删除所有相关记录(类别记录,商店记录,...,...)。
I have created constraints per entity. 我已经为每个实体创建了约束。 So when I remove a user_id(1), engine takes care of removing user_profile(user_id(1)) also.
因此,当我删除user_id(1)时,引擎也负责删除user_profile(user_id(1))。
ALTER TABLE `user_profile`
ADD CONSTRAINT `user_profile_cs1`
FOREIGN KEY (`user_id`) REFERENCES `user`(`user_id`)
ON DELETE CASCADE
But what should I do with pivot tables? 但是我应该如何处理数据透视表? How should I declare constraints or foreign keys on those tables to get the job done and be safe?
我应该如何在这些表上声明约束或外键以完成工作并且安全?
Create a chain of deletion: Add FK constraints to the pivot tables ([C]) or [D] that depends on C, below) 创建删除链:将FK约束添加到数据透视表([C])或[D],这取决于C,如下所示)
[A]
idA
dataA
[B]
idB
dataB
[C]
idC
idA
FOREIGN KEY (idA) REFERENCES A(idA)
ON DELETE CASCADE
idB
FOREIGN KEY (idB) REFERENCES B(idB)
ON DELETE CASCADE
[D]
idD
idC
FOREIGN KEY (idC) REFERENCES C(idC)
ON DELETE CASCADE
Order of operations 运作顺序
Delete(A) -> Delete(C) -> Delete(D)
Delete(B) -> Delete(C) -> Delete(D)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.