我在Symfony中构建了一个页面,它使用Doctrine Query Builder返回结果。该页面还集成了搜索功能。该页面目前运行良好,但我想知道我的代码中的Doctrine Query Builder部分是否可以重新考虑?
因此,我的问题是,与其复制和粘贴同一个查询(正如我在下面的代码($results)中所做的那样),并向查询生成器添加额外的"where"one_answers"setParameter"方法,是否可以将额外的选项附加到第一个查询,这样我就不必重复使用代码了?
$em = $this->getDoctrine()->getManager('managerName');
$results = $em->createQueryBuilder()
->select('d.name','d.createdAt')
->from('ManagerName:Demo', 'd')
->orderBy('d.name')
->getQuery()
->getResult();
if ($form->isSubmitted() && $form->isValid()) {
if (isset($_POST['submit'])) {
$em = $this->getDoctrine()->getManager('managerName');
$results = $em->createQueryBuilder()
->select('d.name', 'd.createdAt')
->from('ManagerName:Demo', 'd')
->where('d.name LIKE :searchTerm')
->orderBy('d.name')
->setParameter('searchTerm', '%' . $search->getSearch() . '%')
->getQuery()
->getResult();
return $this->render('AcmeBundleName:Demo:index.html.twig', [
"form" => $form->createView(),
"results" => $results,
"search" => $search->getSearch(),
]);
}
return $this->redirect($request->getUri());
}
因此,我正在寻找/试图获得的一个例子如下:
$em = $this->getDoctrine()->getManager('managerName');
$query = $em->createQueryBuilder()
->select('d.name','d.createdAt')
->from('ManagerName:Demo', 'd')
->orderBy('d.name')
->getQuery();
$results = $query->getResult();
if ($form->isSubmitted() && $form->isValid()) {
if (isset($_POST['submit'])) {
$em = $this->getDoctrine()->getManager('managerName');
$results = $query->where('d.name LIKE :searchTerm')
->setParameter('searchTerm', '%' . $search->getSearch() . '%');
return $this->render('AcmeBundleName:Demo:index.html.twig', [
"form" => $form->createView(),
"results" => $results,
"search" => $search->getSearch(),
]);
}
return $this->redirect($request->getUri());
}
我不知道是否有可能扩展我之前构建的查询,而且在谷歌上搜索数小时似乎没有返回任何我能联系到的有用来源。
我还查阅了大量的条令文件,包括以下文件,但没有成功:http://www.doctrine-project.org/api/orm/2.2/class-Doctrine.ORM.QueryBuilder.html
提前感谢
在这种情况下,您只需要在执行请求时调用getQuery()
:
$em = $this->getDoctrine()->getManager('managerName');
$query = $em->createQueryBuilder()
->select('d.name','d.createdAt')
->from('ManagerName:Demo', 'd')
->orderBy('d.name');
$results = $query
->getQuery()
->getResult();
if ($form->isSubmitted() && $form->isValid()) {
if (isset($_POST['submit'])) {
$results = $query->where('d.name LIKE :searchTerm')
->setParameter('searchTerm', '%' . $search->getSearch() . '%')
->getQuery()
->getResult();
return $this->render('AcmeBundleName:Demo:index.html.twig', [
"form" => $form->createView(),
"results" => $results,
"search" => $search->getSearch(),
]);
}
return $this->redirect($request->getUri());
}
$query
是DoctrineORMQueryBuilder
的一个实例,您可以在此对象上调用where()
等。
然后您需要调用$query->getQuery()->getResult();
来执行查询。
注意,我还删除了这条重复的行:
$em = $this->getDoctrine()->getManager('managerName');
当然。如果您分离querybuilder对象,这是相当琐碎的。
$qb = $em->createQueryBuilder()
->select('d.name','d.createdAt')
->from('ManagerName:Demo', 'd')
->orderBy('d.name');
$query = $qb->getQuery();