4

我试图为 IN 子句使用学说 entitymanager 运行原始 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 查询的方法。

4

3 回答 3

16

回答:

所以你至少犯了两个错误。首先是@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)
    )
;
于 2013-07-11T09:43:42.887 回答
1

@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();
于 2018-10-25T21:04:49.213 回答
0

你必须让你的数组作为一个数组,不要内爆它。

$params = array(
   'ids'  => $idSArray
);
于 2013-07-11T09:25:52.823 回答