Doctrine 2 DQL IN statement

I have been working with Doctrine 2 for the last month. This week, I really needed to pass an array of values to the Doctrine 2’s DQL IN statement. There is no documentation on Doctrine’s web site for passing in an array of identifiers. Here is how to pass in an array of identifiers into DQL

For Integers


$em->createQuery("SELECT users FROM Entities\User users WHERE users.id IN(".implode('  ',$userIds).")");

For Strings


$em->createQuery("SELECT users FROM Entities\User users WHERE users.id ('".implode("', '", $userUuids)."')");

The Query object does not support flattening arrays and throws the exception, “Doctrine\ORM\Query\QueryException: Invalid parameter number: number of bound variables does not match number of tokens”

9 comments so far

  1. Bas on

    Did you find the solution?

    • redbeardtechnologies on

      That solution is for Doctrine 1.2, not for Doctrine 2.0.

  2. Alan on

    You will get SQL injected if you concatenate parameters that way!!

    • Ulf Reimers on

      Unfortunately Doctrine 2.0 (don’t know if 2.1 is really able to do this) is not able to prepare a statement where you have “where fruit in (“apple”, “banana”, “orange”)”. It always surrounds the value with quotes. So you end up with something “where fruit in (‘”apple”, “banana”, “orange”‘)”.

      Injecting it yourself is the only way right now. I’m really amazed, that no one realized that during developtment of Doctrine2.

  3. Alex on

    Apparently in more recent versions of Doctrine (2.2.2 in my case) it doesn’t work with imploded string, but it’s perfectly happy with arrays.

  4. William Wong on

    Here is how to do it properly:
    $em->createQuery(“SELECT users FROM Entities\User users WHERE users.id IN (:userids)”)
    ->setParameters(array(‘userids’ => $userIds));

    The setParameters will take an array and implode it properly to be used in the “IN” statement.

    • dzi on

      Thanks, that worked (v2.4.0)

  5. deepak on

    how to use the same with createQueryBuilder i am using doctrine wih zf2


Leave a comment