This seems simple but I can't get it right:
There are three entities: Fruit
, Vegetable
and Snack
. Snack has the fields id
, time
and food
. Food is a reference to either one fruit or one vegetable. So it is basically a many-to-one/one-to-many relationship as one snack will always only hold one food. But there is more than one target entity.
How would I map this in Doctrine2?
A simple solution I would have used before knowing Doctrine2 would be to use two fields: food_type
and food_id
. But how can I make a connection from food type to the correct entity? I thought about an array of JoinColumns but can't find a way to connect the correct entity. I also had a look at mapped superclasses because there is a DiscriminatorColumn, but it also seems to be the wrong approach. If I get it right the superclass can't be an entity itself - so I cannot create a food entity.
Any help is appreciated. I'm sure I am missing something simple here.
You can create a (abstract) mapped superclass called
Food
, which can hold some basic information forFruit
andVegetable
.The keyword for your question is
inheritance mapping
, this is the documentation for it: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/inheritance-mapping.html#inheritance-mappingThen you could reference this mapped superclass in your entity relationship.