Symfony2使用Doctrine进行数据库查询方法实例总结
网络编程 2021-07-05 09:10www.168986.cn编程入门
这篇文章主要介绍了Symfony2使用Doctrine进行数据库查询方法,结合实例形式总结分析了基于Doctrine的基本查询、DQL及查询生成器的基本实现方法,需要的朋友可以参考下
本文实例讲述了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( 'SELECT p FROM AcmeStoreBundle:Product p WHERE p.price > :price ORDER BY p.price ASC' )->setParameter('price', '19.99′); $products = $query->getResult();
注:
(1) 获得一个结果可以用:
$product = $query->getSingleResult();
运用 getSingleResult()方法你需要是用try catch语句将它包起来,来保证只返回一个结果,例子如下:
->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程序设计有所帮助。
上一篇:Symfony2联合查询实现方法
下一篇:Symfony2创建页面实例详解
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程