【问题标题】:Symfony2.3 raw sql query with IN ClauseSymfony2.3 带有 IN 子句的原始 sql 查询
【发布时间】:2013-07-09 12:05:00
【问题描述】:

我正在尝试使用教义实体管理器为 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 查询的方法。

【问题讨论】:

标签: php mysql symfony


【解决方案1】:

答案:

所以你至少犯了两个错误。首先是@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)
    )
;

【讨论】:

  • 您的第一个替代方案当前失败,出现数组到字符串的转换错误。第二种选择有效。手册中也说明了这一点:参数列表支持仅适用于 Doctrine\DBAL\Connection::executeQuery() 和 Doctrine\DBAL\Connection::executeUpdate(),不适用于准备好的语句的绑定方法。
【解决方案2】:

@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();

【讨论】:

    【解决方案3】:

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

    $params = array(
       'ids'  => $idSArray
    );
    

    【讨论】:

    • 在这种情况下,我遇到了错误注意:数组到字符串的转换在 .....\vendor\doctrine\dbal\lib\Doctrine\DBAL\Statement.php 第 138 行
    • 你能告诉我更多关于这个错误的信息吗?我不记得确切如何做到这一点,但我认为你不需要内爆你的数组。看docs.doctrine-project.org/projects/doctrine-dbal/en/latest/…,点4.2.2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 2014-05-02
    • 2020-02-22
    • 1970-01-01
    相关资源
    最近更新 更多