2015-02-09 219 views

回答

5

可以使用这样做:

$lastInsertID = $db->getLastInsertID(); 
echo $lastInsertID; 
+1

的可能重复[如何检测使用DAO在Yii中的事务中的最后一个插入ID ?](http://stackoverflow.com/questions/24014286/how-to-detect-the-last-insert-id-within-a-transaction-in-yii-using-dao) – Sadikhasan 2015-02-09 07:01:30

30
Yii::$app->db->createCommand($sql)->execute(); 

然后调用函数getLastInsertID,

$id = Yii::$app->db->getLastInsertID(); 
+2

这是安全的反对竞争条件?例如。用户A插入到'items'中,这个刚刚插入的行的id是5,在A调用getLastInsertID()之后,用户B插入另一行。现在A呼叫说的方法。他会得到5或6吗? – DBX12 2017-03-17 19:36:53

+0

public static function getAutoIncrement($ table_name) { $ q = new Query(); (“TABLE_SCHEMA = DATABASE()AND TABLE_NAME ='”。$ table_name。“'”) (res.txt) - >酮(); if($ res) return $ res [“AUTO_INCREMENT”]; 返回false; } – yousef 2018-01-30 15:33:12