I am attempting to model a relationship which could have two parents, one of them being optional, and the other being mandatory. The design should have the following rules,
- A
House
must exist as the top level parent - A
Bedroom
must have a house as a parent - A
House
can have manyBedroom
s - A
House
can have manyPhoto
s of the house - A
Photo
could also optionally be linked to aBedroom
, i.e. it is a photo of a bedroom in a house - A
User
should only be able to access aHouse
and any child (Bedroom
andPhoto
resources) that are owned by them (through theUserID
field inHouse
table)
My current design looks like this:
+---------+ +-----------+
| House | | Bedroom |
+---------+ +-----------+
+---> HouseID <---+ | BedroomID <----+
| | UserID | +-----+ HouseID | |
| | ... | | ... | |
| +---------+ +-----------+ |
| |
| |
| +-----------+ |
| | Photo | |
| +-----------+ |
| | PhotoID | |
+-----------+ HouseID | OPTIONAL |
| BedroomID +----------------+
| ... |
+-----------+
I currently enforce that a Photo
must be linked to a House
through the FK, so I can perform a JOIN
to get the original UserID
, as I know this key will already exist, but it feels like this is not the right way to go about it.
I ideally want to return Photo
s that are only linked to the House
when querying data about the House
, and then only Photo
s linked to a Bedroom
when querying data about a Bedroom
. I know this is quite easy to do via JOIN
s, but it makes me question whether this is the right design, as it seems to be more "working around the design" than fixing the root problem.
Would it be more useful to use mapping tables here? Or any further ideas on how to improve it?