php 如何使用createCommand在yii2中获取最后插入的id?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28404362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:51:05  来源:igfitidea点击:

How to get last inserted id in yii2 using createCommand?

phpmysqlyii2

提问by Rahul

I am using yii2php framework. I want insert record into database using transaction. How can I get last inserted id using createCommand().

我正在使用yii2php 框架。我想使用transaction. 如何使用createCommand().

Please check following code,

请检查以下代码,

$db = Yii::$app->db;
$sql = $db->createCommand()->insert('user', [
                             'name' => 'test',
                             'email_address' => '[email protected]',
                             'phone_number' => '432432424',
                            ])->execute();

回答by Chandresh M

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

Then call function getLastInsertID,

然后调用函数getLastInsertID,

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

回答by J.K.A.

You can do this using:

您可以使用以下方法执行此操作:

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