国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > 数据库 > access > Symfony2 Doctrine 数据库查询方法总结

Symfony2 Doctrine 数据库查询方法总结

来源:程序员人生   发布时间:2014-09-07 01:20:31 阅读次数:4618次

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 (DoctrineOrmNoResultException $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();

可以在以下链接中获取更多的关于查询生成器的内

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生