I have a schema with a parent-child relationship between two entities. It's a one-to-many, so would naturally be implemented as:
table Parents
id
table Children
id
parent_id
However, I also need to treat one of the children as a special case (Let's call it the "promoted" child). I can think of several ways to do this, including:
Just put an attribute on Children
:
table Parents
id
table Children
id
parent_id
is_promoted
which is obviously flawed, in that the database can't guarantee consistency (At least not through regular foreign key constraints)
Create a foreign-key on the Parents
table:
table Parents
id
promoted_child_id
table Children
id
parent_id
Which was my first inclination, but it does have the obvious downside of a cyclic dependency, so probably not optimal.
Another option, I can think of is to put a second foreign-key on the Children
table:
table Parents
id
table Children
id
parent_id
promoted_parent_id
Which allows me to place a unique index, thereby enforcing database consistency. One problem with this, is that it would be possible to have a meaningless relationship, where a child of parent A lists as promoted of parent B.
The last option I can think of, is to create an intermediary table, e.g.:
table Parents
id
table Children
id
table ParentChildRelationship
parent_id
child_id
is_promoted
Again, I can declare a unique constraint on parent_id
+is_promoted
, enforcing consistency. I'm a bit ambivalent on this one, since it seems like overkill to promote the relationship to a full entity, although the moment I put attributes on it (Which essentially is_promoted
is), I guess it's warranted.
I'd like to know what you would consider the canonical way to handle this problem. In particular, I'm using Rails, so that may influence on what is the most practical solution.
parent_id
andis_promoted
columns ? – Harddennull
meaning false and any value meaning true. But that would be at odds with how Rails do things. – Rosariarosario