KaSkuLL
KaSkuLL

Reputation: 551

Custom repository Symfony

I got an array of IDs (idExam)

And i would like to make a custom respository that on the WHERE it add all IDs.

This this my code:

public function examNotValidated($idExam)
{
    return $this->createQueryBuilder('q')
        ->where('q.creadetby = :creadetby and q.id = :idExam')
        ->setParameter('creadetby', false)
        ->setParameter('idExam', $idExam)
        ->getQuery()
        ->getResult();
}

And i would like something like this:

public function examNotValidated($idExam)
{
    return $this->createQueryBuilder('q')
        ->where('q.creadetby = :creadetby and (q.id = :idExams[0] or q.id = :idExams[1] or q.id = :idExams[3])')
        ->setParameter('creadetby', false)
        ->setParameter('idExams', $idExams)
        ->getQuery()
        ->getResult();
}

Is there anyway to do that?

Upvotes: 2

Views: 42

Answers (1)

karser
karser

Reputation: 1693

You can be using IN expression:

public function examNotValidated(array $ids)
{
    $qb = $this->createQueryBuilder('q');
    return $qb->where('q.creadetby = :creadetby')
        ->andWhere($qb->expr()->in('q.id', $ids))
        ->setParameter('creadetby', false)
        ->getQuery()
        ->getResult();
}

Here is the opposite logic (e.g: q.id = :idExams[0] or q.id = :idExams[1] or q.id = :idExams[3])

public function examNotValidated(array $ids)
{
    $qb = $this->createQueryBuilder('q');

    $orX = $qb->expr()->orX();
    foreach ($ids as $id) {
        $orX->add('q.id = '.$id);
    }

    return $qb->where('q.creadetby = :creadetby')
        ->andWhere($orX);
        ->setParameter('creadetby', false)
        ->getQuery()
        ->getResult();
}

Upvotes: 2

Related Questions