【问题标题】:Laravel 5 - Get newly inserted id in transaction?Laravel 5 - 在事务中获取新插入的 id?
【发布时间】:2016-08-11 19:53:56
【问题描述】:

所以我正在运行一个应该创建用户的事务,并触发一个事件以使用新用户 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 传递给事件?

【问题讨论】:

    标签: laravel laravel-5


    【解决方案1】:

    根据documentation,您应该使用insertGetId 方法

    $newUserId= DB::table('users')->insertGetId([
        'email' => $email,
        'password' => $password
    ]);
    

    【讨论】:

      【解决方案2】:

      您还可以使用 User 模型创建新用户。作为回报,它会为您提供要使用的用户对象。

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

      【讨论】:

      • 从 Laravel 5.5 开始,这在未提交的事务中工作。 id 字段始终为null
      【解决方案3】:
      $id = DB::table('table')->insert( $data )->lastInsertId();
      

      【讨论】:

      • 嘿 stefan,要将代码格式化为一行,请用反引号将其包装起来 `
      • 抛出:Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR) Call to a member function lastInsertId() on boolean 因为 insert() 返回真/假。
      猜你喜欢
      • 2013-07-01
      • 2011-04-20
      • 1970-01-01
      • 2015-09-13
      • 2018-05-26
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多