我的 Symfony2 项目中有一个 Doctrine2 实体(称之为实体 A)。该实体与项目中的另一个实体(称为实体 B)具有 ManyToOne 关系。
实体 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;
}
}
最佳答案
在这种情况下,您应该使用 prePersist
监听器/订阅者而不是 LifecycleCallbacks。
在文档章节中了解有关它们的更多信息 - How to register Event Listeners/Subscribers .
顺便说一句,订阅者被标记为 doctrine.event_subscriber
(当前缺少文档章节)。
关于symfony - Doctrine2 Entity PrePersist - 更新另一个实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20141758/