Aximem
Aximem

Reputation: 732

Symfony | Externalize "where" in a querybuilder

I have a repository with many function like this :

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

But i have to use this part in many others functions :

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

And do something like :

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

Is it possible ? Sorry if it exists, I check in QueryBuilder documentation but I can't find a way to do it.

TY

Upvotes: 0

Views: 74

Answers (2)

Aximem
Aximem

Reputation: 732

Criterias are amazing, TY it does the job. In order to help others, this is how I do it :

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

And :

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

Upvotes: 0

Stephan Vierkant
Stephan Vierkant

Reputation: 10164

I guess Filtering Collections is what you're looking for. Look at this example from the 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);

I also find this answer that will help you.

Upvotes: 1

Related Questions