我有两个实体 - 律师和类别。它们与多对多关联有关。假设示例律师有3个类别。我想通过一系列类别创建搜索律师的功能,它应该只返回拥有数组所有类别的律师。
class Lawyer {
//...
/**
* @ORM\ManyToMany(targetEntity="Dees\KancelariaBundle\Entity\Category")
* @ORM\JoinTable(name="lawyers_has_categories",
* joinColumns={@ORM\JoinColumn(name="lawyer_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="category_id", referencedColumnName="id")}
* )
*
* @var ArrayCollection
*/
protected $categories = null;
//...
}
class Category {
//...
/**
* @ORM\Column(length=255, nullable=true)
*
* @var string
*/
protected $name;
//...
}
public function searchLawyers(array $categories) {
$queryBuilder = $this->createQueryBuilder('lawyer')
->join('lawyer.categories', 'category');
$queryBuilder->andWhere("category.name = :category1");
$queryBuilder->setParameter("category1", "First category");
$queryBuilder->andWhere("category.name = :category2");
$queryBuilder->setParameter("category2", "Second category");
//...
//won't work, return null, but lawyer with these categories exists.
}
我怎样才能实现这样的目标?
答案 0 :(得分:6)
我明白了:
public function searchLawyers(array $categories) {
$queryBuilder = $this->createQueryBuilder('lawyer')
->join('lawyer.categories', 'category');
$queryBuilder->andWhere("category.name in (:categories)");
$queryBuilder->setParameter("categories", $categories);
$queryBuilder->addGroupBy("lawyer.id");
$queryBuilder->andHaving("COUNT(DISTINCT category.name) = :count");
$queryBuilder->setParameter("count", sizeof($categories));
return $queryBuilder->getQuery()->getResult();
}