2013-05-11 182 views
0

我需要將許多實體映射爲一對多到同一個實體主鍵。symfony2 + doctrine2:映射許多實體加入同一個實體複合主鍵

爲了簡便起見,我將嘗試semplify一點點:

假設我有一個新聞和產品表需要進行不同的排序,如果顯示在網站或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 

正如你看到的,我可以有相同的ID重複3次。 我知道這有點髒,也許不是最佳實踐,但每當我需要添加表格(新聞,藝術家,事件等)時,它會爲我節省很多表和實體創建。 我知道使用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

查看文檔中的Class Table Inheritance

您可以使用位置作爲超表新聞產品是鑑別(即你做什麼用的表場)。現在,您只需將目標作爲複合鍵添加到映射的超類(位置)上即可。

只要添加一個新的表格,如事件你只需將它們添加到鑑別地圖和創建具有附加字段的新模式。

+0

感謝mahok,很好的建議! – 2014-03-04 18:13:32

0

非常感謝您的回答,Class Table Inheritance看起來很有趣。

使用它,我會像

/** @Entity */ 
class News extend Position 
{ 
... 
} 

什麼樣,如果在我的情況,我需要的關係定位,也具有相同結構的另一個表(可惜這是我的情況,我需要管理一個可見性表)。 我無法讓新聞擴展位置和可見度。