我正在制作一个表单,通过三个参数搜索用户:
-类别-子类别(多选)-省
用户实体具有与类别的关系,以及与其他参数的关系。如果我只想按分类查找,我想我必须使用以下代码:
$users = $em->getRepository('CASUsuariosBundle:Artist')->findByCategory($category);
但是我如何使用其他参数来做到这一点呢?特别是对于子类别,这是一个多项选择。
用户实体:
/**
* @ORMManyToOne(targetEntity="CASEventBundleEntityCategory", inversedBy="artists")
* @ORMJoinColumn(name="category_id", referencedColumnName="id")
*/
private $category;
/**
* @ORMManyToMany(targetEntity="CASEventBundleEntitySubcategory", inversedBy="artists")
* @ORMJoinTable(name="artists_subcategories",
* joinColumns={@ORMJoinColumn(name="artist_id", referencedColumnName="id")},
* inverseJoinColumns={@ORMJoinColumn(name="subcategory_id", referencedColumnName="id")}
* )
*/
private $subcategories;
/**
* @ORMManyToMany(targetEntity="CASEventBundleEntityProvince", inversedBy="artists")
* @ORMJoinTable(name="artists_provinces",
* joinColumns={@ORMJoinColumn(name="artist_id", referencedColumnName="id")},
* inverseJoinColumns={@ORMJoinColumn(name="province_id", referencedColumnName="id")}
* )
*/
protected $provinces;
搜索控制器:
public function searchAction(Request $request) {
$search = new Search();
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(new SearchType($this->getDoctrine()->getManager()), $search);
$form->setData($search);
$form->handleRequest($request);
if ($form->isValid() || $form->isSubmitted()) {
$category = $form->get('category')->getData();
$subcategories = $form->get('subcategories')->getData();
$province = $form->get('province')->getData();
return $this->showAction($category, $subcategories, $province);
}
return $this->render('CASUsuariosBundle:Profile:search.html.twig', array(
'form' => $form->createView()
));
}
public function showAction($category, $subcategories, $province) {
return $this->render('CASUsuariosBundle:Profile:search_results.html.twig');
}
你应该能够做到
$users = $em->getRepository('CASUsuariosBundle:Artist')->findBy([
'category' => $categories,
'province' => $province,
//...
]);
如果你想要更多的控制权,你可以随时创建一个QueryBuilder
,让你伪造自己的教义请求:
来自symfony文档:
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT p
FROM AppBundle:Product p
WHERE p.price > :price
ORDER BY p.price ASC'
)->setParameter('price', 19.99);
$products = $query->getResult();
供参考:http://symfony.com/doc/current/doctrine.html#querying-for-objects-with-dqlhttp://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html