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

2025-05-29 0 92

本文实例讲述了Symfony2使用Doctrine进行数据库查询方法。分享给大家供大家参考,具体如下:

预定义文中用到的变量:

?

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) 获得一个结果可以用:

?

1
$product = $query->getSingleResult();

运用 getSingleResult()方法你需要是用try catch语句将它包起来,来保证只返回一个结果,例子如下:

?

1

2

3

4

5

6
->setMaxResults(1);

try {

$product = $query->getSingleResult();

} catch (\\Doctrine\\Orm\\NoResultException $e) {

$product = null;

}

(2) setParameter('price', '19.99′);运用这个外部方法来设置查询语句中的 “占位符”price 的值,而不是直接将数值写入查询语句中,有利于防止SQL注入攻击,你也可以设置多个参数:

?

1

2

3

4
->setParameters(array(

'price' => '19.99′,

'name' => 'Foo',

))

3、 运用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();

希望本文所述对大家基于Symfony框架的PHP程序设计有所帮助。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Symfony2使用Doctrine进行数据库查询方法实例总结 https://www.kuaiidc.com/98811.html

相关文章

发表评论
暂无评论