laravel 5.5获取事务内的对象id

时间:2018-02-10 19:32:46

标签: laravel-5.5

我想使用数据库事务,但在事务中使用创建的id。

DB::transaction(function () { 
     $user = User::insert($save_data);// this return bool
     $user = User::insertGetId($save_data); // this returns nothing
})

Laravel 5.5。

由于

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式获取最后插入的ID:

insertGetId

或者,您可以使用DB::transaction(function () { $id = DB::table('users')->insertGetId($save_data); }); 方法:

DB::transaction(function () { 
    // using create
    $user = User::create($save_data);
    // $user->id

    // or using save
    $user = new User;
    $user->foo = $save_data['foo'];
    $user->save();
    // $user->id;
});

使用Eloquent也将返回id:

$students = [
  ['name' => $name1, 'surname' => $surname1, 'avg' => $avg1],
  ['name' => $name2, 'surname' => $surname2, 'avg' => $avg2],
  ['name' => $name3, 'surname' => $surname3, 'avg' => $avg3],
  ['name' => $name4, 'surname' => $surname4, 'avg' => $avg4],
  ['name' => $name5, 'surname' => $surname5, 'avg' => $avg5]
];