Symfony2.3 raw sql query with IN Clause

后端 未结 3 1416
忘了有多久
忘了有多久 2021-01-14 12:43

I was trying to a run raw sql query with doctrine entitymanager for IN clause as shown below.

    $idSArray  = Array ( [0] => 1 [1] => 2 )

    $stm         


        
相关标签:
3条回答
  • 2021-01-14 13:14

    You have to let your array as an array, don't implode it.

    $params = array(
       'ids'  => $idSArray
    );
    
    0 讨论(0)
  • 2021-01-14 13:30

    Answer:

    • List of Parameters Conversion
    • DoctrineDBALTypes Conversion

    So there are at least two mistakes you did. The first is what @Alarid said: you should not implode your array. The second is that you have to use DoctrineDBALTypes Conversion for IN clause when running a prepared statement.

    And finally your query goes this:

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

    Or alternative:

    $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)
        )
    ;
    
    0 讨论(0)
  • 2021-01-14 13:36

    @Hast The second code block you posted works. Adding a new answer so future viewers can reference...

    $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();
    
    0 讨论(0)
提交回复
热议问题