Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a doctrine query inside a DataFixture class?

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

like image 326
ilSavo Avatar asked Aug 01 '13 12:08

ilSavo


1 Answers

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

        // ...

    }
like image 65
Nicolai Fröhlich Avatar answered Oct 08 '22 18:10

Nicolai Fröhlich