2017-01-19 109 views
0

一個實體對象我做的是由三個參數搜索用戶的一種形式:Symfony的 - 查找與關係多對多

- 類別 -Subcategories(可多選) -Province

用戶實體與類別具有關係manyToOne,而具有其他參數的ManyToMany具有關係。如果我想只有categorie找到,我想,我一定要使用此代碼:

$users = $em->getRepository('CASUsuariosBundle:Artist')->findByCategory($category); 

但我怎麼能與其他參數做呢?特別是與子類別,這是一個多選。

用戶實體:

/** 
* @ORM\ManyToOne(targetEntity="\CAS\EventBundle\Entity\Category", inversedBy="artists") 
* @ORM\JoinColumn(name="category_id", referencedColumnName="id") 
*/ 
private $category; 

/** 
* @ORM\ManyToMany(targetEntity="\CAS\EventBundle\Entity\Subcategory", inversedBy="artists") 
* @ORM\JoinTable(name="artists_subcategories", 
*  joinColumns={@ORM\JoinColumn(name="artist_id", referencedColumnName="id")}, 
*  inverseJoinColumns={@ORM\JoinColumn(name="subcategory_id", referencedColumnName="id")} 
*  ) 
*/ 
private $subcategories; 

/** 
* @ORM\ManyToMany(targetEntity="\CAS\EventBundle\Entity\Province", inversedBy="artists") 
* @ORM\JoinTable(name="artists_provinces", 
*  joinColumns={@ORM\JoinColumn(name="artist_id", referencedColumnName="id")}, 
*  inverseJoinColumns={@ORM\JoinColumn(name="province_id", referencedColumnName="id")} 
*  ) 
*/ 
protected $provinces; 

SearchController:

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'); 
} 

回答

0

你應該能夠做到

$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-dql http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html