doctrine: QueryBuilder vs createQuery?

never_had_a_name picture never_had_a_name · Apr 20, 2010 · Viewed 55.3k times · Source

In Doctrine you can create DQL in 2 ways:

EntityManager::createQuery:

$query = $em->createQuery('SELECT u FROM MyProject\Model\User u WHERE u.id = ?1');

QueryBuilder:

$qb->add('select', 'u')
   ->add('from', 'User u')
   ->add('where', 'u.id = ?1')
   ->add('orderBy', 'u.name ASC');

I wonder what the difference is and which should I use?

Answer

jackbravo picture jackbravo · Dec 9, 2010
  1. DQL is easier to read as it is very similar to SQL. If you don't need to change the query depending on a set of parameters this is probably the best choice.

  2. Query Builder is an api to construct queries, so it's easier if you need to build a query dynamically like iterating over a set of parameters or filters. You don't need to do any string operations to build your query like join, split or whatever.