Doctrine DBAL setParameter() with array value
Asked Answered
C

3

18

I'm using doctrine DBAL and have some problem with SQL query as result of a queryBuilder.

$builder = $this->getConnection()->getQueryBuilder();
$builder->select(['id','name','type'])
         ->from('table')
         ->where('id='.(int)$value)
         ->setMaxResults(1);
$builder->andWhere($builder->expr()->in('type', ['first','second']));

echo(builder->getSQL());

$data = $builder->execute()->fetchRow();

And get SQL

SELECT id, name, type FROM table WHERE (id=149) AND (type IN (first,second)) LIMIT 1

And this is the problem, I need that (type IN (first,second)) was encoded as strings like (type IN ('first','second'))

How to do that with query builder in the right way?

Coth answered 6/7, 2015 at 10:6 Comment(0)
K
49

Try with

$builder->andWhere('type IN (:string)');
$builder->setParameter('string', ['first','second'], \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
Kitkitchen answered 6/7, 2015 at 10:37 Comment(5)
Thank you, the second variant with \Doctrine\DBAL\Connection::PARAM_STR_ARRAY works great for me!Coth
First case does not work, because dbal don't wraps strings in array without parameter type.Coth
@SergeyNikolaev you are right but I wasn't able to test it so I've wrote an answer by trying to change array definiton and specifying parameter typeKitkitchen
Hopefully the yet-to-be-finished SO Documentation will help fill these kinds of holes. It took me six hours of googling to find this answer.Mona
\Doctrine\DBAL\Connection::PARAM_STRING_ARRAY is deprecated in newer versions. Use \Doctrine\DBAL\ArrayParameterType::STRING instead.Saltworks
S
4

The array parameters used above are deprecated

New way is

\Doctrine\DBAL\ArrayParameterType:INTEGER
\Doctrine\DBAL\ArrayParameterType:STRING
\Doctrine\DBAL\ArrayParameterType:ASCII
\Doctrine\DBAL\ArrayParameterType:BINARY
$builder->setParameter('type', ['foo','bar'], \Doctrine\DBAL\ArrayParameterType:STRING)
Saunderson answered 10/11, 2023 at 21:35 Comment(0)
H
1
$builder
    ->andWhere($builder->expr()->in('type', ':types'))
    ->setParameter(':types', ['first','second'], \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
Hagan answered 6/3, 2022 at 14:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.