【发布时间】:2013-11-25 07:34:16
【问题描述】:
我的 Symfony2 项目中有一个 Doctrine2 实体(称为实体 A)。该实体与项目中的另一个实体(称为实体 B)具有多对一关系。
实体 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”关系,我认为这是最好的方法(最简单)。如果你必须创建一个不相关的,一个 eventSubstriber#onflush() 将是我会采取的方式。 onflush
标签: symfony doctrine-orm