How to detect the last insert ID within a transaction in Yii using DAO?

user3702874 picture user3702874 · Jun 3, 2014 · Viewed 7.8k times · Source

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

What would be the most suitable way to do that?

Answer

user2227400 picture user2227400 · Jun 3, 2014
$lastInsertID = $connection->getLastInsertID();