在Symfony2 doctrine2查询中获取最后一个插入ID

时间:2017-12-07 06:31:31

标签: php symfony doctrine-orm

在Symfony2 doctrine2查询中获取最后一个插入ID

    $apptQuery = "insert into tbl_student_scores (test_date,updated_by_id) values(:testDate,:loggedinUser)";
    $em = $this->getDoctrine()->getEntityManager();
    $connection = $em->getConnection();
    $Querystatement = $connection->prepare($apptQuery);
    $Querystatement->bindValue('testDate', $test->test_date);
    $Querystatement->bindValue('loggedinUser', $loggedinUser);
    if($Querystatement->execute()){
           var_dump($connection->lastInsertId()); // control coming here but the outpur is bool(false)
    }else{
            echo "query not executed"; 
    }

但是当我写下面的查询时输出变为空。

var_dump($connection->lastInsertId());

1 个答案:

答案 0 :(得分:1)

尝试以下代码。

$apptQuery = "insert into tbl_student_scores (test_date,updated_by_id) values(:testDate,:loggedinUser)";
$em = $this->getDoctrine()->getEntityManager();
$connection = $em->getConnection();
$Querystatement = $connection->prepare($apptQuery);
$Querystatement->bindValue('testDate', $test->test_date);
$Querystatement->bindValue('loggedinUser', $loggedinUser);
$Querystatement->execute();
$insertID = $Querystatement->fetchAll();
$scoreId = $insertID[0]['id'];