Summary of query methods in Symfony

零下一度
Release: 2023-03-12 12:04:02
Original
1550 people have browsed it

This article mainly introduces the Symfonyquery method, and summarizes and analyzes the specific usage techniques of createQuery and getQuery to query data in the form of examples. Friends in need can refer to the following

The examples of this article are described Symfony query method. Share it with everyone for your reference, the details are as follows:

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();
Copy after login

Personal summary:: refers to the meaning of placeholder, to prevent sql injection. So put all the required parameters into 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();
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!