Home  >  Article  >  Backend Development  >  Summary sharing of Symfony query methods

Summary sharing of Symfony query methods

小云云
小云云Original
2018-02-10 13:21:141590browse

This article mainly introduces the Symfony query method to everyone, and summarizes and analyzes the specific usage skills of createQuery and getQuery to query data in the form of examples. Friends in need can refer to it. I hope it can help everyone.

1. How to write 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();

Personal summary:: It means placeholder to prevent SQL injection. So put all the required parameters into the array $params.

2. How to write 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();


Related recommendations:

Symfony2 for Detailed explanation of input time for query example

Detailed explanation of the usage of Symfony2 framework form

Detailed explanation of the method of implementing joint query in Symfony2

The above is the detailed content of Summary sharing of Symfony query methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn