我需要将许多实体作为一对多映射到同一实体主键。
为了简洁起见,我会尝试简化一下:
假设我有新闻和产品表需要以不同的方式订购,如果在网站或ios应用程序中显示。我想只有一个表存储所有表的订单信息(称为“位置”),因为将来我需要管理其他20个表或更多表。
以下是简化表:
_________
|news |
---------
|id (pk) |
|title |
---------
_________
|product |
---------
|id (pk) |
|name |
---------
__________
|position | id + table + target are the composite primary key
----------
|id (pk) | can refer to a news.id or to a product.id depending on table field value
|table(pk) | define if the id refer to a news or to a product
|target(pk)| can be "web" or "ios"
|position | an integer
----------
3 possible position records could be:
id - table - position - target
1 news 1 web
1 news 1 ios
1 product 1 web
正如你所看到的,我可以重复3次相同的id。 我知道这有点脏,也许不是最佳实践,但每次我需要添加表格(新闻,艺术家,活动等)时,它将为我节省大量的表格和实体。 我知道使用Doctrine2来满足我的需求的唯一方法是创建一个xxx_position_web和一个xxx_position_ios表以及我将来必须管理的每个新表的相关实体。
是否可以使用Symfony2中的Doctrine2实体管理类似的内容。 我找到了一个解释与我https://doctrine-orm.readthedocs.org/en/latest/tutorials/composite-primary-keys.html?highlight=composite#identity-through-foreign-entities非常相似的情况的链接,但我无法将其应用到我的情况中。
答案 0 :(得分:0)
在文档中查看Class Table Inheritance。
您可以将位置用作超级表,其中 news 和 product 是鉴别符(即您对表字段执行的操作)。现在,您只需要在映射的超类(位置)上添加目标作为复合键。
每当您添加新表时,例如按或事件,您只需将它们添加到鉴别器地图中,并使用其他字段创建新模型。
答案 1 :(得分:0)
非常感谢您的回答,Class Table Inheritance似乎非常有趣。
使用它我会有类似
的东西/** @Entity */
class News extend Position
{
...
}
如果在我的情况下我需要与位置的关系以及具有相同结构的另一个表(不幸的是这是我的情况,我还需要管理可见性表)。 我不能让新闻扩展到位置和可见性。