1

Doctrine 2 supports many ways to create a query.

One of them is the classical way, through the entity manager;

    $this->getEntityManager()
        ->createQuery('SELECT p FROM AcmeStoreBundle:Product p ORDER BY p.name ASC')
        ->getResult();

And another one is with the query builder:

    $qb = $this->createQueryBuilder('c');
    //...
       ->leftJoin('c.city_state', 's')
       ->where("CONCAT(c.name) LIKE :$field")
       ->setParameter("$field", "%$smartbox%", \PDO::PARAM_STR)
       ->setMaxResults($limit);

At a first glance, the only reason I would use the latter is to help me build conditional queries.

if($value == 'something')
   $qb->add('where', '...');

I was wandering whether there were other reasons I would prefer the first or a second way to write a usual query?

And, are there alternative ways to build a query in Doctrine 2 (except Native queries)?

Edit: I just found a similar question here, but no answer was accepted.

Community
  • 1
  • 1
Tool
  • 12,126
  • 15
  • 70
  • 120

1 Answers1

4

All query builder does is to create dql so there is no functional difference between the two. I always use query builder to avoid having to make long strings and because I find the code easier to read. But it's really a question of taste.

And if you have a repository then query builder eliminates the need to spell out the root class name (i.e. AcmeStoreBundle:Product). Of course to get the repository you probably had to know the name anyways.

Cerad
  • 48,157
  • 8
  • 90
  • 92