I have two entities - Lawyer and Category. They are connected with Many to Many association. Assume that example lawyer has 3 categories. I want to create function to search lawyers by a array of categories, and it should return only lawyers who have all categories from array.
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.
}
How can I achieve something like that?