This article is an example of how Symfony2 uses doctrine to query database queries. Share to everyone for your reference, specific 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 acmestorebundle:product p WHERE p.price >:p Rice ORDER by P.price ASC '
)->setparameter (' Price ', ' 19.99′ ');
$products = $query->getresult ();
Note:
(1) A result can be obtained by:
$product = $query->getsingleresult ();
Using the Getsingleresult () method you need to wrap it in a try catch statement to ensure that only one result is returned, as in the following example:
->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, rather than writing the value directly into the query statement to help prevent SQL injection attacks, you can also set multiple parameters:
->setparameters (Array (
' price ' => ' 19.99′,
' name ' => ' Foo '
))
3, the use of doctrine query generator
$query = $repository->createquerybuilder (' P ')
->where (' p.price >:p rice ')
->setparameter (' Price ', ' 19.99′ '
->orderby (' P.price ', ' ASC ')
->getquery ();
$products = $query->getresult ();
I hope this article will help you with the PHP program design based on Symfony framework.