多目标实体多对一
这看起来很简单,但我做对了:
This seems simple but I can't get it right:
共有三个实体:Fruit
、Vegetable
和Snack
.Snack 有字段 id
、time
和 food
.Food 是对一种水果或一种蔬菜的引用.所以它基本上是一种多对一/一对多的关系,因为一种零食总是只能装一种食物.但目标实体不止一个.
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.
我将如何在 Doctrine2 中映射它?
How would I map this in Doctrine2?
在了解 Doctrine2 之前,我使用的一个简单解决方案是使用两个字段:food_type
和 food_id
.但是我怎样才能将食物类型连接到正确的实体呢?我想过一系列 JoinColumns 但找不到连接正确实体的方法.我还查看了映射的超类,因为有一个 DiscriminatorColumn,但这似乎也是错误的方法.如果我做对了,超类本身就不能是一个实体——所以我不能创建一个食物实体.
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.
推荐答案
您可以创建一个名为Food
的(抽象)映射超类,它可以保存Fruit
和 蔬菜
.
You can create a (abstract) mapped superclass called Food
, which can hold some basic information for Fruit
and Vegetable
.
您问题的关键字是继承映射
,这是它的文档:https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/inheritance-mapping.html#inheritance-mapping
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-mapping
然后你可以在你的实体关系中引用这个映射的超类.
Then you could reference this mapped superclass in your entity relationship.
相关文章