【问题标题】:Doctrine DBAL setParameter() with array value具有数组值的 Doctrine DBAL setParameter()
【发布时间】:2015-09-23 10:23:40
【问题描述】:

我正在使用学说 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'))

如何以正确的方式使用查询生成器做到这一点?

【问题讨论】:

    标签: php mysql symfony doctrine dbal


    【解决方案1】:

    试试

    $builder->andWhere('type IN (:string)');
    $builder->setParameter('string', array('first','second'), \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
    

    【讨论】:

    • 谢谢,\Doctrine\DBAL\Connection::PARAM_STR_ARRAY 的第二个变体对我来说非常有用!
    • 第一种情况不起作用,因为 dbal 不会将字符串包装在没有参数类型的数组中。
    • @SergeyNikolaev 你是对的,但我无法测试它,所以我通过尝试更改数组定义和指定参数类型来写一个答案
    • 希望尚未完成的SO Documentation 将有助于填补这些漏洞。我用谷歌搜索了六个小时才找到这个答案。
    猜你喜欢
    • 2014-06-26
    • 2016-07-04
    • 2012-09-12
    • 2012-12-12
    • 2011-07-15
    • 1970-01-01
    • 2017-07-20
    • 2011-10-07
    • 2014-04-30
    相关资源
    最近更新 更多