symfony - Doctrine2 Entity PrePersist - 更新另一个实体

标签 symfony doctrine-orm

我的 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/

相关文章:

symfony - 使用 Monolog 在 Symfony2 中记录 PHP fatal error

postgresql - Doctrine2 : YEAR, PostgreSQL 的 MONTH、DAY 或 DATE_FORMAT

javascript - 使用java脚本和symfony2更新实体

postgresql - 使用 PostgreSQL : "SQLSTATE[42P01]: Undefined table: 7 ERROR: the relation does not exist" 的 Doctrine2 ManyToMany 关系

symfony2 webprofiler 显示生产环境

symfony - 如何在 symfony 中监听控制台事件?

unit-testing - 在没有 Controller 的情况下测试电子邮件发送

php - 如何将 Doctrine 注入(inject) Symfony2 服务

mysql - select 和 from 可以在 Doctrine 的 QueryBuilder 中参数化吗?

php - symfony2 - 文件上传因表单错误而丢失