2013-11-22 46 views
3

我在Symfony2項目中有一個Doctrine2實體(稱之爲實體A)。該實體與項目中的另一個實體(稱爲實體B)具有ManyToOne關係。Doctrine2實體PrePersist - 更新另一個實體

實體A的狀態屬性爲'活動'或'非活動'。在實體B中只允許有一個「活動」實體A.因此,如果將新實體A添加到現有實體B中,則具有「活動」狀態的先前實體A需要更新爲「非活動」。

實現此目標的最佳方法是什麼?

我在想LifeCycle方法(prePersist),但我懷疑它是否有效,因爲它是另一個實體,它比我堅持的實體更新。

一個代碼示例:

class EntityA 
{ 
    const ACTIVE = 'active'; 
    const INACTIVE = 'inactive'; 

    private $id; 
    private $status; 
    private $entityB; 

    public function prePersist() 
    { 
     $currentEntityA = $this->entityB->getCurrentEntityA(); 
     if ($currentEntityA) { 
      $currentEntityA->setStatus(self::INACTIVE); 
     } 
    } 
} 

class EntityB 
{ 
    private $id; 
    private $name; 
    private $entityA; 

    public function getCurrentEntityA() 
    { 
     foreach($this->entityA as $row){ 
      if ($row->getStatus() == EntityA::ACTIVE) { 
       return $row; 
      } 
     } 
     //no entityA found so return null 
     return null; 
    } 
} 
+0

在這種情況下,您可以瀏覽「A」關係,我認爲這是最好的方式ch(最簡單)。 如果你不得不創建一個不相關的,那麼eventSubstriber#onflush()將是我會採取的方式。 [onflush](http://docs.doctrine-project.org/en/2.0.x/reference/events.html#onflush) – juanmf

回答

1

你應該在這種情況下使用prePersist聽衆/用戶,而不是LifecycleCallbacks。

在文檔章節 - How to register Event Listeners/Subscribers中瞭解更多關於它們的信息。

btw訂閱者被標記爲doctrine.event_subscriber當前缺少文檔章節)。

+0

謝謝!我會在星期一檢查一下 –

1

您可以使用幾種方法

  1. 主義事件監聽器
  2. 服務層
  3. 數據庫觸發器

在你的情況,我認爲更好地使用服務和移動你的業務邏輯有