我正在尝试使用doctrine entitymanager为IN子句运行原始sql查询,如下所示。
$idSArray = Array ( [0] => 1 [1] => 2 )
$stmt = $this->getDoctrine()->getEntityManager()
->getConnection()
->prepare('SELECT t1.id , t1.name , t2.start_date , t2.end_date
FROM table1 t1 , table2 t2
WHERE t1.id = t2.matchId AND t1.id IN (:ids)');
$params = array(
'ids' => implode( ",", $idSArray )
);
$stmt->execute($params);
$results = $stmt->fetchAll();
但我只得到Id = 1的结果。如果我将WHERE IN条件硬编码为
WHERE t1.id = t2.matchId AND t1.id IN (1,2)');
然后获得两个ID的结果。谁能告诉我在传递$ params数组时我做错了什么。我还打印了输出1,2的内爆结果。所以我无法找到错误以及使用IN子句执行原始sql查询的方法。
答案 0 :(得分:12)
答案:
所以你做的至少有两个错误。第一个是@Alarid所说的:你不应该破坏你的阵列。第二个是在运行预准备语句时必须使用DoctrineDBALTypes Conversion
作为IN clause
。
最后你的查询是这样的:
$stmt = $this->getDoctrine()->getEntityManager()
->getConnection()
->prepare('SELECT t1.id , t1.name , t2.start_date , t2.end_date
FROM table1 t1 , table2 t2
WHERE t1.id = t2.matchId AND t1.id IN (:ids)');
$stmt->bindValue('ids', $idSArray, \Doctrine\DBAL\Connection::PARAM_INT_ARRAY);
$stmt->execute();
或替代方案:
$stmt = $this->getDoctrine()->getEntityManager()
->getConnection()
->executeQuery('SELECT t1.id , t1.name , t2.start_date , t2.end_date
FROM table1 t1 , table2 t2
WHERE t1.id = t2.matchId AND t1.id IN (:ids)',
array('ids' => $idSArray),
array('ids' => \Doctrine\DBAL\Connection::PARAM_INT_ARRAY)
)
;
答案 1 :(得分:0)
你必须让你的数组作为一个数组,不要破坏它。
$params = array(
'ids' => $idSArray
);
答案 2 :(得分:0)
@Hast您发布的第二个代码块有效。添加新答案,以便将来的观众参考...
$ids = [1,2];
$sql = "SELECT t1.id , t1.name , t2.start_date , t2.end_date
FROM table1 t1 , table2 t2
WHERE t1.id = t2.matchId AND t1.id IN (?)";
$stmt = $this->getEntityManager()->getConnection()->executeQuery(
$sql,
[$ids],
[\Doctrine\DBAL\Connection::PARAM_INT_ARRAY] // for an array of strings use PARAM_STR_ARRAY
);
$data = $stmt->fetchAll();