本文實(shí)例講述了Symfony2使用Doctrine進(jìn)行數(shù)據(jù)庫(kù)查詢方法。分享給大家供大家參考,具體如下:
預(yù)定義文中用到的變量:
1
2
|
$em = $this ->getDoctrine()->getEntityManager(); $repository = $em ->getRepository( 'AcmeStoreBundle:Product' ) |
1、基本方法
1
2
3
4
5
6
|
$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
1
2
3
4
|
$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(); |
注:
(1) 獲得一個(gè)結(jié)果可以用:
1
|
$product = $query ->getSingleResult(); |
運(yùn)用 getSingleResult()方法你需要是用try catch語(yǔ)句將它包起來(lái),來(lái)保證只返回一個(gè)結(jié)果,例子如下:
1
2
3
4
5
6
|
->setMaxResults(1); try { $product = $query ->getSingleResult(); } catch (\Doctrine\Orm\NoResultException $e ) { $product = null; } |
(2) setParameter('price', '19.99′);運(yùn)用這個(gè)外部方法來(lái)設(shè)置查詢語(yǔ)句中的 “占位符”price 的值,而不是直接將數(shù)值寫(xiě)入查詢語(yǔ)句中,有利于防止SQL注入攻擊,你也可以設(shè)置多個(gè)參數(shù):
1
2
3
4
|
->setParameters( array ( 'price' => '19.99′, 'name' => 'Foo' , )) |
3、 運(yùn)用Doctrine的查詢生成器
1
2
3
4
5
6
|
$query = $repository ->createQueryBuilder( 'p' ) ->where( 'p.price > :price' ) ->setParameter( 'price' , '19.99′) ->orderBy( 'p.price' , 'ASC' ) ->getQuery(); $products = $query ->getResult(); |
希望本文所述對(duì)大家基于Symfony框架的PHP程序設(shè)計(jì)有所幫助。