Home  >  Article  >  php教程  >  Symfony2 uses Doctrine for database query method example summary

Symfony2 uses Doctrine for database query method example summary

高洛峰
高洛峰Original
2016-12-26 11:31:041287browse

The example in this article describes how Symfony2 uses Doctrine to perform database queries. 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) Obtained A result can be used:

$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 "placeholder" price in the query statement The value, instead of directly writing the value into the query statement, is helpful to prevent SQL injection attacks. You can also set multiple parameters:

->setParameters(array(
'price' => '19.99′,
'name' => 'Foo',
))

3, Using 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 in PHP programming based on the Symfony framework.

For more Symfony2 using Doctrine for database query method examples and summary related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn