Question

How can I access the EntityManager or a repository class inside a DataFixture in order to create a query?

Was it helpful?

Solution

If your fixture implements ContainerAwareInterface you have full access to the container and can obtain one of your entity-managers from there.

once you have the entity-manager you can get the repository or create a query using DQL or the 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();

        // ...

    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top