Doctrine2实体PrePersist-更新另一个实体 [英] Doctrine2 Entity PrePersist - Update another entity

查看:75
本文介绍了Doctrine2实体PrePersist-更新另一个实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Symfony2项目中有一个Doctrine2实体(称为实体A)。该实体与项目中的另一个实体(称为实体B)具有ManyToOne关系。

I have a Doctrine2 entity (call it entity A) in my Symfony2 project. This entity has a ManyToOne relationship with another entity (call it entity B) in the project.

实体A的状态属性为活动或非活动。实体B中仅允许一个活动实体A。因此,如果将新的实体A添加到现有实体B,则具有活动状态的先前的实体A需要更新为非活动。

Entity A has a status property which is 'active' or 'inactive'. There's only one 'active' entity A allowed in entity B. So, if a new entity A is added to an existing entity B, the previous entity A, which has an 'active' status, needs to be updated to 'inactive'.

实现此目标的最佳方法是什么?

What is the best approach to achieve this?

我在考虑LifeCycle方法(prePersist),但是我怀疑这是否行得通,因为它是另一个实体,而不是我保留的实体。

I was thinking about the LifeCycle methods (prePersist), but I doubt if this works, because it's another entity which is updated than the entity I persist.

代码示例:

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;
    }
}


推荐答案

您可以使用几种方法


  1. Doctrine事件侦听器

  2. 服务层

  3. 数据库触发器

在您的情况下,我认为最好使用服务并将业务逻辑移到那里

In your situation I think better to use services and move your business logic there

这篇关于Doctrine2实体PrePersist-更新另一个实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆