How to get a Respository from an Entity?

后端 未结 4 1358
遇见更好的自我
遇见更好的自我 2020-12-25 14:01

I have an Entity called Game with a related Repository called GameRepository:

/**
 * @ORM\\Entity(repositoryClass=\"...\\GameReposi         


        
4条回答
  •  攒了一身酷
    2020-12-25 14:29

    You actually can get the repository in your entity and only during a lifecycle callback. You are very close to it, all you have to do is to receive the LifecycleEventArgs parameter.

    Also see http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html

    use Doctrine\ORM\Event\LifecycleEventArgs;
    
    /**
     * @ORM\Entity(repositoryClass="...\GameRepository")
     * @ORM\HasLifecycleCallbacks()
     */
    class Game {
        /**
         * @ORM\prePersist
         */
        public function setSlugValue( LifecycleEventArgs $event ) {
            $entityManager = $event->getEntityManager();
            $repository    = $entityManager->getRepository( get_class($this) );
    
            $this->slug = $repository->createUniqueSlugForGame();
        }
    }
    

    PS. I know this is an old question, but I answered it to help any future googlers.

提交回复
热议问题