我尝试在 WHERE IN 语句中的 dbal 查询生成器中绑定参数 : [1, 2]
我试图$qb->expr()->in()
更改为字符串版本,但没有任何变化
查询生成器创建
$qb = $this->_em->getConnection()->createQueryBuilder()
->select('c.id AS id')
->from('category', 'c')
->andWhere($qb->expr()->in('c.id', ':categories'))->setParameter('categories', [1, 2], DoctrineDBALConnection::PARAM_INT_ARRAY);
执行:
$qb->execute()->fetchAll();
错误 :Array to string conversion
期望将整数数组绑定到查询生成器语句
总是喜欢引用文档。
// 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 ExprFunc instance
来源: 原则查询生成器文档
所以从本质上讲,除非类别是数字,否则你必须用占位符填充数组并设置它们,或者如果它们是数字,你可能可以使用这个例子。
我假设你有一个实体,它有一个具有ManyToMany或ManyToOne的类别实体, 你可以只传递一个类别数组,如果数组正确制作如下,它应该可以工作:
qb = $this->_em->getConnection()->createQueryBuilder()
->select('c.id AS id')
->from('category', 'c')
->andWhere($qb->expr()->in('c.id',':categories'))->setParameter('categories', $categoriesArray);
否则,您可以尝试通过内爆数组来将 setParameter 与 id 数组一起使用:
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]));