首页 >后端开发 >php教程 >总结Symfony中查询的方法介绍

总结Symfony中查询的方法介绍

零下一度
零下一度原创
2017-07-02 11:57:441609浏览

这篇文章主要介绍了Symfony查询方法,结合实例形式总结分析了createQuery与getQuery查询数据的具体使用技巧,需要的朋友可以参考下

本文实例讲述了Symfony查询方法。分享给大家供大家参考,具体如下:

1. createQuery的写法


$sql = 'SELECT COUNT(DISTINCT(g.goodsId)) FROM AppBundle:GoodsIndex g WHERE g.status = :status';
$params = array(
 'status' => GoodsIndex::STATUS_NORMAL,
);
if (!empty($keywords)) {
 $params['keywords'] = "%{$keywords}%";
 $sql .= ' AND g.keywords like :keywords ';
}
 if (!empty($warehouseIdList)) {
  $params['warehouseIdList'] = $warehouseIdList;
  $sql .= " AND g.warehouseId IN :(warehouseIdList)";
 }
$goodsNum = $this->entityManager->createQuery($sql)->setParameters($params)->getSingleScalarResult();

个人总结::是指占位符的意思,防止sql注入。所以把所有需要的参数做成数组$params里面。

2. getQuery的写法


$orderBy = 'p.'.$searchOptions['orderBy'];
$repository = $this->entityManager
 ->getRepository('AppBundle:GoodsIndex');
$query = $repository->createQueryBuilder('p');
$query->select('DISTINCT(p.goodsId)');
$query->where('p.keywords like :keywords')
 ->setParameter('keywords', "%{$searchOptions['keywords']}%")
 ->andwhere('p.status = :status')
 ->setParameter('status', GoodsIndex::STATUS_NORMAL)
 ->orderBy($orderBy, $searchOptions['order'])
 ->setFirstResult($pagination['pageSize'] * ($pagination['page'] - 1))
 ->setMaxResults($pagination['pageSize']);
if (!empty($searchOptions['warehouseIdList'])) {
 $query->andWhere($query->expr()->in('p.warehouseId', $searchOptions['warehouseIdList']));
}
$goodsIndexList = $query->getQuery()->getResult();

以上是总结Symfony中查询的方法介绍的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn