Mysql 使用Lumen/Laravel的事务中最后插入的id

Mysql 使用Lumen/Laravel的事务中最后插入的id,mysql,laravel,transactions,lumen,Mysql,Laravel,Transactions,Lumen,如何获取最后插入的id 我使用的代码如下: DB::insert(“插入到成员(名称,电子邮件)值($name,$email)”); $lastID=DB::getPdo()->lastInsertId()使用查询生成器时,Laravel具有插入行并返回新创建的id的功能 $lastid = DB::table('members')->insertGetId(['name' => $name, 'email' => $email]); 您可以轻松获得: $last_id =

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

DB::insert(“插入到成员(名称,电子邮件)值($name,$email)”);

$lastID=DB::getPdo()->lastInsertId()使用查询生成器时,Laravel具有插入行并返回新创建的
id
的功能

$lastid = DB::table('members')->insertGetId(['name' => $name, 'email' => $email]);
您可以轻松获得:

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

如果使用模型,技巧应该非常简单。假设您是
成员
模型。因此,当您尝试插入记录时,它将返回插入的记录作为响应

/** 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
}

试试$dataset=array('column_id'=>1,'name'=>Dayle')$column_id=DB::table('users')->insertGetId($dataset,'column_id');是否可以在事务之外使用$lastid?当然,一旦查询返回此值,
$lastid
就只是一个局部变量