【问题标题】:How to get last inserted id in yii2 using createCommand? [duplicate]如何使用 createCommand 在 yii2 中获取最后插入的 id? [复制]
【发布时间】:2015-02-09 06:58:46
【问题描述】:

我正在使用yii2 php 框架。我想使用transaction 将记录插入数据库。如何使用 createCommand() 获取最后插入的 id。

请检查以下代码,

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

【问题讨论】:

    标签: php mysql yii2


    【解决方案1】:
    Yii::$app->db->createCommand($sql)->execute();
    

    然后调用函数getLastInsertID,

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

    【讨论】:

    • 这对竞争条件安全吗?例如。用户 A 插入 items 并且这个刚刚插入的行的 id 是 5 并且在 A 调用 getLastInsertID() 之前用户 B 插入另一行。现在 A 调用所述方法。他会得到 5 个还是 6 个?
    【解决方案2】:

    你可以这样做:

    $lastInsertID = $db->getLastInsertID();
    echo $lastInsertID;
    
    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 2011-08-16
    • 2016-10-24
    • 2016-06-01
    • 1970-01-01
    相关资源
    最近更新 更多