1-33
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Symfony2 – Franz Jordán 2011<br />
$query = $em->createQuery('SELECT ....')<br />
->setMaxResults(1);<br />
try {<br />
$product = $query->getSingleResult();<br />
} catch (\Doctrine\Orm\NoResultException $e) {<br />
}<br />
// ...<br />
$product = null;<br />
The DQL syntax is incredibly powerful, allowing you to easily join between entities (the topic<br />
ofrelations will be covered later), group, etc. For more information, see the official<br />
Doctrine Doctrine Query Language documentation.<br />
Setting Parameters<br />
Take note of the setParameter() method. When working with Doctrine, it's always a good idea<br />
to set any external values as "placeholders", which was done in the above query:<br />
... WHERE p.price > :price ...<br />
You can then set the value of the price placeholder by calling the setParameter()method:<br />
->setParameter('price', '19.99')<br />
Using parameters instead of placing values directly in the query string is done to prevent SQL<br />
injection attacks and should always be done. If you're using multiple parameters, you can set<br />
their values at once using the setParameters() method:<br />
->setParameters(array(<br />
'price' => '19.99',<br />
'name' => 'Foo',<br />
))<br />
Using Doctrine's Query Builder<br />
Instead of writing the queries directly, you can alternatively use Doctrine's QueryBuilder to do<br />
the same job using a nice, object-oriented interface. If you use an IDE, you can also take<br />
advantage of auto-completion as you type the method names. From inside a controller:<br />
$repository = $this->getDoctrine()<br />
->getRepository('AcmeStoreBundle:Product');<br />
$query = $repository->createQueryBuilder('p')<br />
->where('p.price > :price')<br />
->setParameter('price', '19.99')<br />
->orderBy('p.price', 'ASC')<br />
->getQuery();<br />
$products = $query->getResult();<br />
The QueryBuilder object contains every method necessary to build your query. By calling<br />
thegetQuery() method, the query builder returns a normal Query object, which is the same<br />
object you built directly in the previous section.<br />
For more information on Doctrine's Query Builder, consult Doctrine's Query<br />
Builder documentation.<br />
Custom Repository Classes<br />
In the previous sections, you began constructing and using more complex queries from inside a<br />
controller. In order to isolate, test and reuse these queries, it's a good idea to create a custom<br />
repository class for your entity and add methods with your query logic there.<br />
92