Using EntityManager inside Doctrine 2.0 entities

前端 未结 4 2151
执笔经年
执笔经年 2020-11-27 03:50

I have 2 entities: Country (id, name) and Mapping (id, object, internalId, externalId). Country and Mapping are not connected with associations (because Mapping has rows not

4条回答
  •  佛祖请我去吃肉
    2020-11-27 04:27

    This might not be the best idea, but there is a simple way to do this.

    The UnitOfWork class in doctrine will hydrate any entity which implements ObjectManagerAware with the entity manager and class metadata for that entity.

    All you have to do to get the entity manger in your entity is implement the interface as shown in the example below:

    use Doctrine\Common\Persistence\Mapping\ClassMetadata;
    use Doctrine\Common\Persistence\ObjectManager;
    use Doctrine\Common\Persistence\ObjectManagerAware;
    
    /**
     * @ORM\Entity
     */
    class MyEntity implements ObjectManagerAware
    {
        public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata)
        {
            $this->em = $objectManager;
        }
    }
    

    If you create a new entity rather than querying it from the database, you will need to set the entity manager manually, for example with a setter method.

提交回复
热议问题