This example describes how to use Doctrine to query databases in Symfony2. For your reference, we will share the following variables: $ em $ this-getDoctrine ()-getEntityManager (); $ repository $ em-getRepository (AcmeStoreBundle: product) 1. Basic Method $ repository-f
This example describes how to use Doctrine to query databases in Symfony2. For your reference, we will share the following variables: $ em = $ this-getDoctrine ()-getEntityManager (); $ repository = $ em-getRepository ('acmestorebundle: product') 1. Basic Method $ repository-f
This example describes how to use Doctrine to query databases in Symfony2. We will share this with you for your reference. The details are as follows:
Variables used in the predefined text:
$em = $this->getDoctrine()->getEntityManager();$repository = $em->getRepository('AcmeStoreBundle:Product')
1. Basic Methods
$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, you can 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 '). This external method is used to set the "Placeholder" price value in the query statement, instead of directly writing the value into the query statement, which helps prevent SQL injection attacks, you can also set multiple parameters:
->setParameters(array('price' => '19.99′,'name' => 'Foo',))
3. Query Builder using Doctrine
$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 help you design PHP programs based on the Symfony framework.