Search code examples
phpsymfonydoctrineabstract-syntax-treedql

Doctrine AST custom walkers


I'm using Doctrine with Symfony 2. I have lots of DQL queries that share common parts. I have found, it's possible to solve this problem using Doctrine's custom walkers that modify AST. Below is an example of what I would like to accomplish:

Transform

SELECT a
FROM AcmeBundle:SomeEntity a
WHERE a.someColumn = 5

to

SELECT a
FROM AcmeBundle:SomeEntity a
LEFT JOIN a.someOtherEntity b
WHERE a.someColumn = 5 AND (b.someOtherColumn = 2 OR b.someTotallyOtherColumn = 3)

AST walker should add a left join - or multiple left joins and add conditions in WHERE part.

I was reading the docs (http://docs.doctrine-project.org/en/2.0.x/cookbook/dql-custom-walkers.html), but there is just one example. The code used in example already looks complex to me plus I wasn't able to find any other documentation, so that's the reason I'm asking here.

Thanks!


Solution

  • Consider using query builder instead:

    $qb = $entityManager->createQueryBuilder();
    $qb->addSelect('a');
    $qb->from('AcmeBundle:SomeEntity','a');
    $qb->andWhere(... someColumn = 5 ...);
    

    You could execute the above query directly or add more to it with:

    $qb->leftJoin('a.someOtherEntity','b');
    $qb->andWhere(... additional conditions ...);