最后插入的 id 内部事务 Lumen/Laravel

Last inserted id Inside transaction with Lumen/Laravel

如何获取最后插入的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),它仍然不起作用。 我在这里做错了什么?

使用查询构建器时,Laravel 具有插入行的函数 insertGetId 和 returns 新创建的 id.

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

轻松搞定:

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

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

/** Insert record **/
$member = Member::create(['name' => $name, 'email' => $email])

/** your last inserted id will be in $member **/
$lastInsertedId = $member->id

希望这对你有用。

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

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
}

这对我有用

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
    }