如何在DataFixture类中执行doctrine查询?

时间:2013-08-01 12:24:25

标签: symfony doctrine-orm fixtures

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

1 个答案:

答案 0 :(得分:12)

如果你的夹具实现ContainerAwareInterface,你就可以完全访问容器,并可以从那里获得一个实体经理。

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

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();

        // ...

    }