如何使用 DAO 在 Yii 中检测事务中的最后一个插入 ID?

2022-01-04 00:00:00 transactions php yii dao lastinsertid

这是源代码,我需要检测ID(见下面两个查询之间的标记位置).

That's the source code, I need to detect the ID (see the marked position between the two queries below).

$connection = Yii::app()->db;
$transaction=$connection->beginTransaction();
try {

    $q = "INSERT INTO `someTable1` .... ";      
    $connection->createCommand($q)->execute(); // Single Row Inserted

    // HERE!! How to get the last insert ID from query above

    $q = "INSERT INTO `someTable2` ....
          WHERE id = LAST_INSERT_ID_FROM_FIRST_QUERY ";
    $connection->createCommand($q)->execute();

    $transaction->commit();

} catch (Exception $e) {
    // react on exception   
    $trans->rollback();
} 

最合适的方法是什么?

推荐答案

$lastInsertID = $connection->getLastInsertID();

相关文章