I had a Movie
entity and an Image
entity where a Movie
should have an Image
and I put them in a one-to-one relationship -
Movie
-----
id (PK)
title
Image
-----
id (PK)
base64
movie_id (FK to Movie, Unique)
I made Movie
the parent entity based on the logic that "a Movie
can exist without an Image
, but an Image
cannot exist without a Movie
" - which did make sense. But then came Director, Actor, User etc, each of which too, requires to have an Image
.
I want an Image
to be uniquely identifiable through any other entities, i.e. same Image should not belong to any two different entities (of similar or different types). That is very much possible if I keep Image
as child of other entities. But adding new foreign-keys to Image
seemed a bad approach -
- this will require more schema changes in future
- only one of the foreign-key fields is going to have a non-Null value
Also, the initial logic doesn't hold anymore - an Image
now can exist without a Movie
because it might be an Image
of something else.
To solve the issue -
- I considered to make
Image
the parent entity -
Image
-----
id (PK)
base64
Movie
-----
id (PK)
title
image_id (FK to Image, Unique)
Entities are required to keep track of their own Image
and no schema change in existing Image
entity, but -
- the idea of
Image
being parent in a one-to-one relationship withMovie
(or other entities) somehow felt wrong - two different types of entities can now reference the same
Image
- now I'm loosing the cascade delete of
Image
entity
- I considered having lookup table like
MovieImage
-
Movie
-----
id (PK)
title
Image
-----
id (PK)
base64
MovieImage
----------
movie_id (PK, FK to Movie)
image_id (FK to Image, Unique)
This would do, but -
- an
Image
can sill be referenced by two different types of entities - it complicates a bit the models and data operations at application level
- still loosing the cascading
So, what would be the best approach to go for and what are the general design practices in such scenario?