Symfony2使用Doctrine进行数据库查询方法实例总结
本文实例讲述了Symfony2使用Doctrine进行数据库查询方法。分享给大家供大家参考,具体如下:
预定义文中用到的变量:
$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(
'SELECTpFROMAcmeStoreBundle:ProductpWHEREp.price>:priceORDERBYp.priceASC'
)->setParameter('price','19.99′);
$products=$query->getResult();
注:
(1)获得一个结果可以用:
$product=$query->getSingleResult();
运用getSingleResult()方法你需要是用trycatch语句将它包起来,来保证只返回一个结果,例子如下:
->setMaxResults(1);
try{
$product=$query->getSingleResult();
}catch(\Doctrine\Orm\NoResultException$e){
$product=null;
}
(2)setParameter('price','19.99′);运用这个外部方法来设置查询语句中的“占位符”price的值,而不是直接将数值写入查询语句中,有利于防止SQL注入攻击,你也可以设置多个参数:
->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程序设计有所帮助。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下