[英]Postgres single foreign key to different tables
I have some postgres tables: 我有一些postgres表:
Component Component_A Component_B
----------- ------------ ------------
id id id
component_type type type
component_id foo_col bar_col
I would like Component
to be able to reference either Component_A
or Component_B
, depending on the combination of component_type
and component_id
. 我希望
Component
能够引用Component_A
或Component_B
,这取决于component_type
和component_id
的组合。 Component_A
and Component_B
have different structures, so they can't be stored within the same table. Component_A
和Component_B
具有不同的结构,因此不能将它们存储在同一表中。 In a sense, Component
is 1 to 1 with both Component_A
and Component_B
. 从某种意义上说,
Component
与Component_A
和Component_B
都是1比1。
What is the best way to model this in Postgres? 在Postgres中对此建模的最佳方法是什么?
If I have understood you correctly, I would put in Component_A a foreign key for id and type referencing component_type and component_id in Component. 如果我对您的理解正确,我会在Component_A中放入一个外键作为ID,并在Component中引用component_type和component_id。 Same for Component_B.
与Component_B相同。 If you put an ON DELETE CASCADE in those two foreign key, whenever a Component was deleted, their corresponding Component_A or Component_B would be deleted, keeping your database without orphan records on those tables.
如果将ON DELETE CASCADE放在这两个外键中,则每当删除一个Component时,它们对应的Component_A或Component_B都会被删除,从而使数据库中没有这些表上的孤立记录。
If you are looking for the other way around (deleting a record in Component_A and having the corresponding Component deleted), I'm not sure if it can be done with foreign keys, but you can achieve that by using a TRIGGER for DELETE in Component_A and Component_B that takes care of deleting the Component related record. 如果您正在寻找另一种方法(删除Component_A中的记录并删除相应的Component),则不确定是否可以通过外键来完成,但是您可以通过在Component_A中使用TRIGGER进行DELETE来实现和负责删除与组件相关的记录的Component_B。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.