Doctrine2 Entity PrePersist - Update another entit

2019-04-11 20:28发布

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.

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?

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.

A code example:

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

2条回答
走好不送
2楼-- · 2019-04-11 21:04

You should use a prePersist listener / subscriber instead of LifecycleCallbacks in this case.

Read more about them in the documentation chapter - How to register Event Listeners/Subscribers.

btw a subscriber is tagged with doctrine.event_subscriber (currently missing the doc chapter).

查看更多
家丑人穷心不美
3楼-- · 2019-04-11 21:06

You can use several approaches

  1. Doctrine Event Listeners
  2. Service layer
  3. Database triggers

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

查看更多
登录 后发表回答