Symfony 2,QueryBuilder,多个和Where具有相同的参数

Posted

技术标签:

【中文标题】Symfony 2,QueryBuilder,多个和Where具有相同的参数【英文标题】:Symfony 2, QueryBuilder, multiple andWhere with same parameter 【发布时间】:2015-01-31 23:41:21 【问题描述】:

我有两个实体 - 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.
    

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

【问题讨论】:

【参考方案1】:

我想通了:

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

【讨论】:

以上是关于Symfony 2,QueryBuilder,多个和Where具有相同的参数的主要内容,如果未能解决你的问题,请参考以下文章

Symfony的。存储库方法。在查询参数(queryBuilder)中绑定用户

Symfony/QueryBuilder:“myEntityAlias.myEntity.id”<- 可能吗?

Symfony2,如何使用 KnpPaginatorBundle 和 QueryBuilder 传递参数排序和方向

Symfony 5,Doctrine queryBuilder OneToMany 关系

symfony doctrine QueryBuilder到数组结果

Symfony3 QueryBuilder使用Subquery进行更新