7

如何访问 DataFixture 中的 EntityManager 或存储库类以创建查询?

4

1 回答 1

13

如果您的夹具实现ContainerAwareInterface了您对容器的完全访问权限,并且可以从那里获得您的实体管理器之一。

拥有实体管理器后,您可以获取存储库或使用 DQL 或查询构建器创建查询。

namespace Vendor\YourBundleBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class LoadCharacterData implements FixtureInterface, ContainerAwareInterface
{
    private $container;

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    public function load()
    {
        $em = $this->container->get('doctrine')->getEntityManager('default');

        // example using DQL
        $query = $em->createQuery('SELECT u FROM YourBundle\Entity\User u WHERE u.name = your_name');
        $users = $query->getResult();

        // example query using repository
        $repository = $em->getRepository('YourBundle:User');
        $entities = $repository->findBy(array('name' => 'your_name'));

        // example using queryBuilder
        $qb = $repository->createQueryBuilder('u');
        $qb
            ->where('u.name = :name')
            ->setParameter('name', 'your_name')
            ->orderBy('u.name');

        $users = $qb->getQuery()->getResult();

        // ...

    }
于 2013-08-01T14:53:18.390 回答