6

I have an array of id:

Id_array; //array(2) { [0]=> int(9) [1]=> int(10) } 

I simply want to select the users using Id_array; I managed to do this when I don't have an array but just an integer:

$query = $em->createQuery('SELECT u FROM Users u WHERE u.id = ?1');
$query->setParameter(1, 9); // I tested the value 9 here
$users = $query->getResult(); 

How can I fetch all the users that correspond to Id_array?

3 Answers 3

26

Or without the query builder:

$query = $em->createQuery('SELECT u FROM Users u WHERE u.id IN (:id)');
$query->setParameter('id', array(1, 9));
$users = $query->getResult();
Sign up to request clarification or add additional context in comments.

Comments

9

In case someone runs into something similar, I used the query builder, The key point is to use the IN statement.

//...
$qb = $this->createQueryBuilder('u');
$qb->add('where', $qb->expr()->in('u.id', ':my_array'))
->setParameter('my_array', $Id_array);

2 Comments

your solution works best because it handles strings too, the accepted answer works only with integers
Above didn't work for me. I had to do setParameter('my_array', $Id_array, Connection::PARAM_INT_ARRAY). Maybe because I use DBAL query builder, not ORM one.
7

On doctrine 2 is implemented by the repository now since 2.1 or 2.2

findBy(array('id' => array(1, 2, 3, 4, 5));

1 Comment

Exactly what I was looking for! Thx!

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.