本文主要和大家介紹了Symfony查詢方法,結合實例形式總結分析了createQuery與getQuery查詢數據的具體使用技巧,需要的朋友可以參考下,希望能幫助到大家。
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中文網其他相關文章!