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