Home >Backend Development >PHP Tutorial >Symfony2 uses Doctrine for database query method example summary, symfony2doctrine_PHP tutorial
This article describes how Symfony2 uses Doctrine for database query. Share it with everyone for your reference, the details are as follows:
Predefined variables used in the text:
$em = $this->getDoctrine()->getEntityManager(); $repository = $em->getRepository('AcmeStoreBundle:Product')
1. Basic method
$repository->find($id); $repository->findAll(); $repository->findOneByName('Foo'); $repository->findAllOrderedByName(); $repository->findOneBy(array('name' => 'foo', 'price' => 19.99)); $repository->findBy(array('name' => 'foo'),array('price' => 'ASC'));
2. DQL
$query = $em->createQuery( 'SELECT p FROM AcmeStoreBundle:Product p WHERE p.price > :price ORDER BY p.price ASC' )->setParameter('price', '19.99′); $products = $query->getResult();
Note:
(1) To obtain a result, use:
$product = $query->getSingleResult();
To use the getSingleResult() method, you need to wrap it with a try catch statement to ensure that only one result is returned. The example is as follows:
->setMaxResults(1); try { $product = $query->getSingleResult(); } catch (\Doctrine\Orm\NoResultException $e) { $product = null; }
(2) setParameter('price', '19.99'); Use this external method to set the value of the "placeholder" price in the query statement, instead of directly writing the value into the query statement, which is helpful to prevent SQL injection attack, you can also set multiple parameters:
->setParameters(array( 'price' => '19.99′, 'name' => 'Foo', ))
3. Use Doctrine’s query builder
$query = $repository->createQueryBuilder('p') ->where('p.price > :price') ->setParameter('price', '19.99′) ->orderBy('p.price', 'ASC') ->getQuery(); $products = $query->getResult();
I hope this article will be helpful to everyone’s PHP program design based on the Symfony framework.