Doctrine ORM:如何使用 nn 连接表定义 1-n 关系
所以,这有点复杂:我有两个表,例如 cats
和 dogs
。 它们处于多对多关系(可以称为友谊
或其他),因此 Doctrine 会自动为我创建一个带有适当字段的表cats_dogs
。 (默认情况下,即 rowid、cat_id、dog_id
。)
现在,假设我有第三个表 award
,我想在其中奖励这些友谊之一。因此,这里我需要一个引用 cats_dogs
中的一行的字段。然而,由于这个表在我的模型之间并不真正存在,(Doctrine 为我处理它)最优雅的解决方案是什么?
最后,我希望在我的奖励
模型中包含两个字段,一个猫
和一个狗
,它们需要处于友谊之中。
我正在使用注释驱动程序。
So, this is a bit complicated: I have two tables, say cats
and dogs
.
They are in a many-to-many relationship (could be called friendships
or whatever), so that Doctrine automatically creates a table cats_dogs
for me with the appropriate fields. (that is rowid, cat_id, dog_id
per default.)
Now, imagine I have a third table, award
, where I want to award one of these friendships. Here I therefore need a field that references one row in cats_dogs
. However, since this table does not really exist between my models, (Doctrine handles it for me) what would be the most elegant solution for this?
In the end, I want in my award
model two fields, a cat
and a dog
, who need to be in a friendship.
I am using the annotation driver.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是什么阻止您手动创建 m:n 表而不是让教条为您创建?
What stops you from manually creating the m:n table instead of having doctrine do it for you?
该 Doctrine 的目标是从 E/R 模式映射对象并更轻松地访问对象连接。因此我相信Doctrine自动提供的表
cats_dogs
是必要的。它简洁并达到了其目的,即它提供了猫的所有狗的列表,反之亦然,狗的所有猫的列表。因此,我可以得出结论,最好创建一个名为
Award
的第三个实体(除了Cat
和Dog
),它提供一对一的一种与Cat
的关系,另一种与Dog
的一对一关系。使其与cats_dogs
表一致只能由您决定,默认情况下不是 Doctrine 任务。例如,您可以使用一些级联持久选项。我相信这是 Doctrine 最有效的解决方案。
最后一点,请考虑每个表都应该映射一个或多个实体之间的特定关系,事实上,表
cats_dogs
表示友谊关系,而表cats_dogs
表示友谊关系。 >Award 将代表两个朋友之间的获奖关系关系。The Doctrine aims is to map objects from an E/R schema and to make easier the access to object connections. Therefore I believe that the table
cats_dogs
automatically provided by Doctrine is necessary as it is. It is concise and hits its purposes, i.e. it provides a list of all dogs of a cat or, vice versa, all the cats of a dog.Thus, I can conclude that it is preferable to create a third entity (besides
Cat
andDog
) namedAward
which provides a one-to-one relationship withCat
and another one-to-one relationship withDog
. Making it consistent with thecats_dogs
table is only up to you, and is not a Doctrine task by default. E.g., you can use some cascade persist option.I believe that this is the most effective solution with Doctrine.
As a final remark, consider that each table should map a specific relationship between one or more entities, and in fact the table
cats_dogs
represents the friendship relationships, while the tableAward
will represent the awarded relationship relationship between two friends.