0

I try to bind parameter : [1, 2] in dbal querybuilder in WHERE IN statement

I tried to change $qb->expr()->in() to string version but nothing changed

QueryBuilder creation

$qb = $this->_em->getConnection()->createQueryBuilder()
            ->select('c.id AS id')
            ->from('category', 'c')
            ->andWhere($qb->expr()->in('c.id', ':categories'))->setParameter('categories', [1, 2], \Doctrine\DBAL\Connection::PARAM_INT_ARRAY);

Execution:

$qb->execute()->fetchAll();

Error : Array to string conversion

Expects to bind array of integers to querybuilder statement

Vytautas Saulis
  • 141
  • 2
  • 6

2 Answers2

1

always love to quote documentation.

// Example - $qb->expr()->in('u.id', array(1, 2, 3))
// Make sure that you do NOT use something similar to $qb->expr()->in('value', array('stringvalue')) as this will cause Doctrine to throw an Exception.
// Instead, use $qb->expr()->in('value', array('?1')) and bind your parameter to ?1 (see section above)
public function in($x, $y); // Returns Expr\Func instance

source: doctrine querybuilder docs

so essentially, unless the categories are numbers, you have to fill an array with placeholders and set those, or if they are numbers, you probably can just use the example.

Jakumi
  • 8,043
  • 2
  • 15
  • 32
-1

I assume you have an entity which has a ManyToMany or ManyToOne with a Category entity, You could just pass an array of Categories and it should work if the array is properly made like so :

qb = $this->_em->getConnection()->createQueryBuilder()
            ->select('c.id AS id')
            ->from('category', 'c')
     ->andWhere($qb->expr()->in('c.id',':categories'))->setParameter('categories', $categoriesArray);

Otherwise, you can try to use setParameter with your array of id by imploding the array :

qb = $this->_em->getConnection()->createQueryBuilder()
            ->select('c.id AS id')
            ->from('category', 'c')
            ->andWhere($qb->expr()->in('c.id', ':categories'))->setParameter('categories', implode(",",[1, 2]));
Dylan KAS
  • 4,840
  • 2
  • 15
  • 33