sajad torkamani

In a nutshell

Doctrine’s QueryBuilder gives you an API that lets you conditionally construct a DQL query.

<?php
// $qb instanceof QueryBuilder

// example3: retrieve the associated EntityManager
$em = $qb->getEntityManager();

// example4: retrieve the DQL string of what was defined in QueryBuilder
$dql = $qb->getDql();

// example5: retrieve the associated Query object with the processed DQL
$q = $qb->getQuery();

Recipes

Create a query builder

<?php
// $em instanceof EntityManager

// example1: creating a QueryBuilder instance
$qb = $em->createQueryBuilder();

Get DQL

$qb = $entityManager->createQueryBuilder();
$qb->select('u')->from('User', 'u');
var_dump($qb->getDQL());

Get SQL

$dql = "SELECT u FROM User u";
$query = $entityManager->createQuery($dql);
var_dump($query->getSQL());

Get query object

// example5: retrieve the associated Query object with the processed DQL
$q = $qb->getQuery();

Dynamically build conditional expressions

<?php
// $qb instanceof QueryBuilder

$qb->select(array('u')) // string 'u' is converted to array internally
   ->from('User', 'u')
   ->where($qb->expr()->orX(
       $qb->expr()->eq('u.id', '?1'),
       $qb->expr()->like('u.nickname', '?2')
   ))
   ->orderBy('u.surname', 'ASC');

Execute a query

$query = $qb->getQuery();
$result = $query->getResult();

Sources

Tagged: Doctrine