【问题标题】:Last inserted id Inside transaction with Lumen/Laravel使用 Lumen/Laravel 的最后插入的 id 内部事务
【发布时间】:2018-12-25 02:05:25
【问题描述】:

如何获取最后插入的 id 我使用以下有效的代码:

DB::insert("INSERT INTO members (name,email)values($name,$email)");
$lastID = DB::getPdo() -> lastInsertId();

但是下面的代码没有给我最后插入的 id。

DB::transaction(function () {
    $result = DB::insert("INSERT INTO members (name,email)values($name,$email)");
    $lastID = DB::getPdo() -> lastInsertId();
}, 5);
return $lastID;

即使我在事务之外使用变量($lastID),它仍然不起作用。 我在这里做错了什么?

【问题讨论】:

标签: mysql laravel transactions lumen


【解决方案1】:

使用查询构建器时,Laravel 有函数 insertGetId 插入行并返回新创建的 id

$lastid = DB::table('members')->insertGetId(['name' => $name, 'email' => $email]);

【讨论】:

  • 可以在事务外使用$lastid吗?
  • 当然,一旦查询返回这个值$lastid只是一个局部变量
【解决方案2】:

请参阅下面的示例代码。希望对您有所帮助。

public function testModel($data) {
    $id = DB::transaction(function() use ($data) {
        $record_id = DB::table('users')->insertGetId($data);

        DB::update('update users set votes = 100 where name = ?', ['John']);

        return $record_id;
    });

    return $id; // this will return the last inserted id which is the $record_id inside the DB::transaction
}

【讨论】:

    【解决方案3】:

    你可以轻松搞定:

    $last_id = DB::table('members')->insertGetId(['name => $name, 'email => $email]);
    

    【讨论】:

      【解决方案4】:

      这对我有用

      public function testModel($data) {
              $last_id = DB::transaction(function() use ($data) {
                  Table::create($data);
                  return DB::getPdo()->lastInsertId();
              });
          
              return $last_id; // this will return the last inserted id
          }
      

      【讨论】:

        【解决方案5】:

        如果你使用模型,技巧应该很简单。假设您拥有Member 模型。因此,当您尝试插入记录时,它会返回插入的记录作为响应。

        /** Insert record **/
        $member = Member::create(['name' => $name, 'email' => $email])
        
        /** your last inserted id will be in $member **/
        $lastInsertedId = $member->id
        

        希望这对你有用。

        【讨论】:

          猜你喜欢
          • 2014-01-31
          • 1970-01-01
          • 1970-01-01
          • 2015-01-19
          • 1970-01-01
          • 1970-01-01
          • 2014-07-23
          • 1970-01-01
          相关资源
          最近更新 更多