Home > php教程 > PHP开发 > Symfony2 uses Doctrine for database query method example summary

Symfony2 uses Doctrine for database query method example summary

高洛峰
Release: 2016-12-26 11:31:04
Original
1304 people have browsed it

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')
Copy after login

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'));
Copy after login

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();
Copy after login

Note:

(1) Obtained A result can be used:

$product = $query->getSingleResult();
Copy after login

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;
}
Copy after login

(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',
))
Copy after login

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();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template