1-33
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Symfony2 – Franz Jordán 2011<br />
Deleting an Object<br />
Deleting an object is very similar, but requires a call to the remove() method of the entity<br />
manager:<br />
$em->remove($product);<br />
$em->flush();<br />
As you might expect, the remove() method notifies Doctrine that you'd like to remove the given<br />
entity from the database. The actual DELETE query, however, isn't actually executed until<br />
the flush()method is called.<br />
Querying for Objects<br />
You've already seen how the repository object allows you to run basic queries without any work:<br />
$repository->find($id);<br />
$repository->findOneByName('Foo');<br />
Of course, Doctrine also allows you to write more complex queries using the Doctrine Query<br />
Language (DQL). DQL is similar to SQL except that you should imagine that you're querying for<br />
one or more objects of an entity class (e.g. Product) instead of querying for rows on a table<br />
(e.g.product).<br />
When querying in Doctrine, you have two options: writing pure Doctrine queries or using<br />
Doctrine's Query Builder.<br />
Querying for Objects with DQL<br />
Imaging that you want to query for products, but only return products that cost more<br />
than 19.99, ordered from cheapest to most expensive. From inside a controller, do the<br />
following:<br />
$em = $this->getDoctrine()->getEntityManager();<br />
$query = $em->createQuery(<br />
'SELECT p FROM AcmeStoreBundle:Product p WHERE p.price > :price ORDER BY p.price ASC'<br />
)->setParameter('price', '19.99');<br />
$products = $query->getResult();<br />
If you're comfortable with SQL, then DQL should feel very natural. The biggest difference is that<br />
you need to think in terms of "objects" instead of rows in a database. For this reason, you<br />
select fromAcmeStoreBundle:Product and then alias it as p.<br />
The getResult() method returns an array of results. If you're querying for just one object, you<br />
can use the getSingleResult() method instead:<br />
$product = $query->getSingleResult();<br />
The getSingleResult() method throws a Doctrine\ORM\NoResultExceptionexception if no<br />
results are returned and aDoctrine\ORM\NonUniqueResultException if more than one<br />
result is returned. If you use this method, you may need to wrap it in a try-catch block and<br />
ensure that only one result is returned (if you're querying on something that could feasibly<br />
return more than one result):<br />
91