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