Laravel 5 - 在事务中获取新插入的id?

4

我正在运行一个事务,应该创建一个用户,并触发一个事件以使用新的用户ID执行其他操作,包括创建一个设置表,其中设置表中的外键user_id是新创建的user_id(前提是事务可以正常工作)。

这是我目前的代码:

DB::beginTransaction();

try {
    DB::table('users')->insert([
              'email' => $email,
              'password' => $password
    ]);

    event(new UserWasStored($newUserId)); // How do I get the $newUserId?
}
catch(\Exception $e) {
    DB::rollback();
}

DB::commit();

在事务中如何将$newUserId传递给事件?

3个回答

8
根据文档,你应该使用insertGetId方法进行操作。
$newUserId= DB::table('users')->insertGetId([
    'email' => $email,
    'password' => $password
]);

1

你也可以使用User模型来创建一个新用户。作为回报,它将提供给你用户对象以便操作。

$user = User::create([
    'email'     => 'john@example.com',
    'password'  => bcrypt('your-password')
]);

dd($user->id);

1
从Laravel 5.5开始,在未提交的事务中,这个操作是*不起作用的。id字段始终为null - user1643723

0
$id = DB::table('table')->insert( $data )->lastInsertId();

嗨,Stefan,要将代码格式化为单行,请使用反引号 ` 将其包裹。 - Wonka
抛出异常:Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR),因为 insert() 返回 true/false,所以在布尔值上调用 lastInsertId() 方法。 - voidstate

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接