0

I use Doctrine in my PHP application (but not using Symfony). I try to make a dynamic query with only one addWhere/orWhere.

Here is my code:

$alias = 'a';
$key = 'id';
$qb = $repo->createQueryBuilder($alias);
$qb->select($alias);
$qb->andWhere($alias . ' = ' . $key);

// Key is "id" and value is a dynamic array "[1, 2, 3, 6...]"
$qb->setParameter($key, $value);

If value is only "1" I got this DQL :

SELECT a FROM contact a WHERE a = :id

And it works. But with value as an array, I want to do this query without multiple "andOr" because my array is dynamic. Is there a method to automatically add (addWhere or orWhere) to get that automatically using my array:

SELECT a FROM contact a WHERE a = :id OR a:= id OR a:= id

I know I can do a for loop myself but I want to know if there is already an existing method in doctrine.

1 Answer 1

1

You should use IN instruction.

$alias = 'a';
$key = 'id';
$values = [1, 2, 3];
$qb = $repo->createQueryBuilder($alias);
$qb->select($alias);
$qb->where(\sprintf("%s.%s IN (:values)", $alias, $key));

$qb->setParameter('values', $values);

I hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Works great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.