1

我有一个来自 Symfony2 项目的对象。下面是代码。命名空间 Acme\UserBundle\Form\Model;

use Symfony\Component\Validator\Constraints as Assert;
use Acme\UserBundle\Entity\User;

class Registration
{
    /**
     * @Assert\Type(type="Acme\UserBundle\Entity\User")
     */
    protected $user;

    ...

    public function setUser(User $user)
    {
        //Get the EntityManager here!!!!
        $group = $em
            ->getRepository('AcmeUserBundle:Group')
            ->findOneByName('Customers');
        $this->user->addGroup($group);
    }
....

}

那么,正如代码中强调的那样,如何让 EntityManager 使用 Doctrine 检索实体?提前致谢

4

1 回答 1

0

好的,解决了!

我只需要将 EntityManager 传递给控制器​​内的 Registration 类的构造函数。

use Symfony\Component\Validator\Constraints as Assert;
use Acme\UserBundle\Entity\User;


class Registration
{
    /**
    * @Assert\Type(type="Acme\UserBundle\Entity\User")
    */
    protected $user;

    ...

    protected $em;    

    public function __construct($em) {
       $this->em = $em;
    }    

    public function setUser(User $user)
    {
        $this->user = $user;
        $group = $this->em->getRepository('AcmeUserBundle:Group')
            ->findOneByName('Customers');
        $this->user->addGroup($group);
    }
...
}

总之非常感谢。

于 2012-04-18T08:54:59.983 回答