Legend:
- PK (Blue): Primary key
- FK (Green): Foreign key
- PFK (Blue): Primary Key and Foreign Key at the same time
How to model a diamond like (if term is correct) relationship? Better to explain using a simplified example:
There is organization
, item
and tag
entities.
My aim is to model:
- Every
tag
is unique by itself and belongs to a single organization. - Every
item
is unique by itself and belongs to a single organization. - Items have many tags (joined using M2M table) and related
tag
/item
pairs must belong to same organization. (i.e. item from organization A cannot pair with a tag from organization B)
I diagrammed two alternative solutions, but none of them satisfied me.
Diagram 1 breaks 3rd aim: items
and tags
are unique by themselves using id
as primary key, but there is nothing to stop insert pairs into item_tag
which belong to different organization.
Diagram 2 does not break, but bends 1st and 2nd aims: organization_id
is added as a Primary and Foreign Key to item
and tag
tables and item_tag.organization_id
column references both. This prevents pairs from different organization. tag.id
and item.id
columns are part of a unnecessary composite primary key now, because in reality single id
column represents uniqueness of the item
and tag
.
How can I model those requirements correctly?