Symfony |在查询构建器中外化“where”

时间:2016-04-28 15:07:09

标签: doctrine-orm doctrine query-builder symfony

我有一个包含许多功能的存储库:

$this->createQueryBuilder('q')
            ->where('q.deleted = :deleted')
            ->setParameter('deleted', false)
            ->getQuery()
            ->getResult();

但我必须在许多其他功能中使用这部分:

->where('q.deleted = :deleted')
->setParameter('deleted', false)

做类似的事情:

$this->createQueryBuilder('q')
     ->checkIfDeleted()
     ...

有可能吗?对不起,如果它存在,我检查QueryBuilder文档,但我找不到办法。

TY

2 个答案:

答案 0 :(得分:1)

我猜过滤收藏是您正在寻找的内容。从Doctrine documentation

中查看此示例
$group          = $entityManager->find('Group', $groupId);
$userCollection = $group->getUsers();

$criteria = Criteria::create()
    ->where(Criteria::expr()->eq("birthday", "1982-02-17"))
    ->orderBy(array("username" => Criteria::ASC))
    ->setFirstResult(0)
    ->setMaxResults(20)
;

$birthdayUsers = $userCollection->matching($criteria);

我也发现this answer可以帮到你。

答案 1 :(得分:0)

标准是惊人的,TY它完成了这项工作。为了帮助他人,我就是这样做的:

$questionsArray =  $this->createQueryBuilder('q')
        ->getQuery()
        ->getResult();

    $questionsArrayCollection = new ArrayCollection($questionsArray); 
    // I'm force to do this because the querybuilder returns an Array and I need an ArrayCollection, criteria can be used only on collections.

    return $questionsArrayCollection->matching($this->addCriteriaQuestionNotDeleted());

并且:

public function addCriteriaQuestionNotDeleted()
{
    return Criteria::create()
            ->where(Criteria::expr()->eq("deleted", false));
}