• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Symfony2使用Doctrine进行数据库查询方法实例总结_PHP

php 搞代码 4年前 (2022-01-26) 8次浏览 已收录 0个评论

本文实例讲述了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′);$pro<i style="color:transparent">本#文来源gaodai$ma#com搞$$代**码网$</i><button>搞代gaodaima码</button>ducts = $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程序设计有所帮助。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Symfony2使用Doctrine进行数据库查询方法实例总结_PHP

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址