Symfony - 查找具有多对多关系的实体对象

时间:2017-01-19 10:57:44

标签: php symfony doctrine-orm

我正在制作一个用三个参数搜索用户的表单:

- 类别 - 子类别(多选) -Province

用户实体与Categories关联manyToOne,与其他参数关联ManyToMany。如果我只想按类别查找,我想我必须使用此代码:

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

1 个答案:

答案 0 :(得分:0)

你应该能够做到

$users = $em->getRepository('CASUsuariosBundle:Artist')->findBy([
    'category' => $categories,
    'province' => $province,
    //...
]);

如果你想要更多的控制权,你总是可以创建一个QueryBuilder,这将允许你伪造自己的学说请求:

来自symfony docs:

$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