gpt4 book ai didi

php - Symfony 2,QueryBuilder,具有相同参数的多个andWhere

转载 作者:行者123 更新时间:2023-12-02 07:26:53 24 4
gpt4 key购买 nike

我有两个实体 - Lawyer 和 Category。它们与多对多关联相关联。假设示例律师有 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.
}

我怎样才能实现这样的目标?

最佳答案

我想通了:

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

关于php - Symfony 2,QueryBuilder,具有相同参数的多个andWhere,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27271230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com