[英]Doctrine ManyToMany distinction field - possible?
我正在嘗試使用帶有Doctrine 2的單個表/類來實現可以應用於多個實體的訂閱模型。請參閱下面的示例說明。
架構(yml):
User:
type: entity
table: users
id: int
name: string
Subscription:
type: entity
table: subscriptions
id: int
object_type: string
object_id: int
user_id: int
Feature:
type: entity
table: features
id: int
name: string
manyToMany:
subscribers:
targetEntity: User
joinTable:
name: subscriptions
joinColumns:
object_id:
referencedColumnName: id
Issue:
type: entity
table: issues
id: int
subject: string
manyToMany:
subscribers:
targetEntity: User
joinTable:
name: subscriptions
joinColumns:
object_id:
referencedColumnName: id
表數據看起來像這樣:
users:
| id | name |
| 1 | John |
| 2 | Joe |
features:
| id | name |
| 1 | Feature A |
| 2 | Feature B |
issues:
| id | subject |
| 1 | Issue 1 |
| 2 | Issue 2 |
subscriptions:
| id | object_type | object_id | user_id
| 1 | feature | 1 | 1 <- John is subscribed to Feature A
| 2 | issue | 1 | 1 <- John is subscribed to Issue 1
我期望得到的是一個額外的“區別”字段,我可以在模型的manyToMany關系中有例如:
manyToMany:
subscribers:
targetEntity: User
joinTable:
name: subscriptions
joinColumns:
object_id:
referencedColumnName: id
object_type:
value: feature
我知道后者的靈魂並不存在於學說中,但我很好奇你會如何解決這種情況?
我們的想法是將此訂閱“特質”動態擴展到其他實體(例如,項目,團隊等)
我是否必須為所有訂閱引入單獨的表,如feature_subscribers
和issue_subscribers
..等等,還是有更優雅的方式?
更新:
我不想從訂閱方知道目標對象的類型。 我只找得到的用戶(收集User
從實體(特征,問題等))。
您可以通過使用帶有鑒別器映射的單表繼承來實現此訂閱表布局。 (有關示例,請參閱此博客文章 )
假設您的訂閱管理器服務的subscribe(User $user, SubscriptionObject $object)
方法接收用戶對象和要訂閱的對象(功能或問題)。
現在,訂閱管理器創建了一個IssueSubscription
或FeatureSubscription
對象並將其保留。 這樣,doctrine會根據您的鑒別器映射正確保存object_type
。
最后,您必須添加一個偵聽器/訂閱者,以動態調整*** Subscription對象的關系映射(與Issue或Feature的關系),以便始終將外鍵保存到object_id
。
更快的方法可能是使用IssueSubscription-> Issue和FeatureSubscription->以表格布局結尾的特征關系映射,如下所示:
subscriptions:
| id | object_type | feature_id | issue_id | user_id
| 1 | feature | 1 | NULL | 1
| 2 | issue | NULL | 1 | 1
...然后在您的BaseSubscription
添加一個簡單的getObject()
方法,如return ( $this->feature != null ) ? $this->feature : $this->issue;
return ( $this->feature != null ) ? $this->feature : $this->issue;
會忽略聽眾的需要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.