我正在使用 DBAL 原则,并且由于 queryBuilder 的 SQL 查询存在一些问题。
$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();
并获取SQL
SELECT id, name, type FROM table WHERE (id=149) AND (type IN (first,second)) LIMIT 1
这就是问题所在,我需要将 (type IN (first,second)) 编码为字符串,例如 (type IN ('first','second'))
如何以正确的方式使用查询生成器来做到这一点?
尝试使用
$builder->andWhere('type IN (:string)');
$builder->setParameter('string', ['first','second'], \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
$builder
->andWhere($builder->expr()->in('type', ':types'))
->setParameter(':types', ['first','second'], \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
上面使用的数组参数已被弃用
新方法是
\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)