【发布时间】:2018-06-07 03:10:34
【问题描述】:
在我的 RegistrationController@store 中,我正在执行以下操作:
- 创建用户(用户:
hasMany()积分、hasOne()个人资料、@987654324@ 角色) - 附加一个角色(角色:
belongsToMany()User) - 创建个人资料(个人资料:
belongsTo()用户) - 将初始分数设置为 0(分数:
belongsTo()用户)
我意识到如果这些步骤之一失败,例如,如果由于连接速度慢而无法创建配置文件,我的应用程序就会中断。这是我的存储方法:
public function store(){
$profile = new Profile();
$points = new Points();
$this->validate(request(),[
'name' => 'required',
'username' => 'required|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required|confirmed',
'role_id' => 'required|between:1,2'
]);
$user = User::create([
'name' => request('name'),
'username' => request('username'),
'email' => request('email'),
'password' => bcrypt(request('password'))
]);
$role_student = Role::where('title', 'Student')->first();
$role_parent = Role::where('title', 'Parent')->first();
if(request()->input('role_id') == 1){
$user->roles()->attach($role_student);
} else if(request()->input('role_id') == 2){
$user->roles()->attach($role_parent);
}
$profile->user_id = $user->id;
$profile->date_of_birth = Carbon::createFromDate(request('year'),request('month'),request('day'));
$profile->institution = request('institution');
$profile->class = request('class');
$profile->division = request('division');
$profile->photo = 'propic/default.png';
$profile->bio = 'I am a Member!';
$profile->social_link = 'http://facebook.com/zuck';
$profile->save();
auth()->login($user);
\Mail::to($user)->send(new Welcome($user));
$points->updateOrCreateAndIncrement(0);
return redirect()->home();
}
值得一提的是,所有数据均来自注册表。我怎样才能一次执行所有这些步骤(或者,在一个语句中),以便如果语句执行成功,我将有一个完美同步的注册,否则,不会有数据被持久化到数据库中?
【问题讨论】:
-
我想你在关注transactions?
-
@Don'tPanic 我不知道幕后发生了什么,但如果我将所有语句从 store() 方法移到
DB::transaction的闭包中,我会在安全区吗?