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

btxsgosb  于 2022-11-09  发布在  其他
关注(0)|答案(4)|浏览(152)

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

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

最合适的方法是什么呢?

gdrx4gfi

gdrx4gfi1#

$lastInsertID = $connection->getLastInsertID();
c2e8gylq

c2e8gylq2#

您可以尝试两种方法,这里getLastInsertID是方法,而lastInsertID是属性,

$lastInsertID = $connection->getLastInsertID();

$lastInsertID = $connection->lastInsertID;

更多信息http://www.yiiframework.com/doc/api/1.1/CDbConnection

wxclj1h5

wxclj1h53#

我创造这个是为了解决那个问题

public static function getAutoIncrement($table_name)
{
    $q = new Query();
    $res = $q->select("AUTO_INCREMENT")
        ->from('INFORMATION_SCHEMA.TABLES')
        ->where("TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '" . $table_name . "'")
        ->one();
    if ($res)
        return $res["AUTO_INCREMENT"];
    return false;
}
2eafrhcq

2eafrhcq4#

对于任何感兴趣的人:
saveMethod中的ActiveRecord执行类似于

\Yii::$app->db->schema->insert($tableName, $values)

结果是

["id" => 1]

模式以它自己的方式做到这一点:

public function insert($table, $columns)
{
    $command = $this->db->createCommand()->insert($table, $columns);
    if (!$command->execute()) {
        return false;
    }
    $tableSchema = $this->getTableSchema($table);
    $result = [];
    foreach ($tableSchema->primaryKey as $name) {
        if ($tableSchema->columns[$name]->autoIncrement) {
            $result[$name] = $this->getLastInsertID($tableSchema->sequenceName);
            break;
        }

        $result[$name] = isset($columns[$name]) ? $columns[$name] : $tableSchema->columns[$name]->defaultValue;
    }

    return $result;
}

我建议使用schema->insert,它支持复合标识符,并使用序列名来获取最后一个ID

相关问题