The example in this paper describes the database query method Symfony2 using doctrine. Share to everyone for your reference, 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 (' 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 >:p rice ORDER by P.price ASC ')-> ; Setparameter (' Price ', ' 19.99′ '); $products = $query->getresult ();
Note:
(1) To obtain a result can be used:
$product = $query->getsingleresult ();
Using the Getsingleresult () method you need to wrap it up with 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 statement, rather than writing the value directly into the query statement, to prevent SQL injection attacks, you can also set multiple parameters:
->setparameters (' 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 ();
It is hoped that this article is helpful to the PHP program design based on Symfony framework.