我需要同时插入多个表,使用事务的想法似乎是唯一的出路。但雄辩的交易并没有像我预期的那样发挥作用。这是我的代码片段。
DB::transaction(function(){
try{
//Create new tenant
$ewTenant = new Tenant;
$ewTenant->tenant_name = $request->input('tenant_name');
$ewTenant->tenant_url = $request->input('tenant_url');
$ewTenant->tenant_email = $request->input('tenant_email');
$ewTenant->tenant_phone = $request->input('tenant_phone');
$ewTenant->contact_name = $request->input('contact_name');
$ewTenant->plan_id = $request->input('plan_id');
$ewTenant->save();
//Create a default administrator group
$newGroup = new UserGroup;
$newGroup->tenant_id = $ewTenant->id;
$newGroup->user_group_name = "Administrator";
$newGroup->description = "Default Administrator's Group";
//Create a Supper admin for the tenant created
$newUser = new Users;
$newUser->tenant_id = $ewTenant->id;
$newUser->username = "Administrator";
$newUser->password = bcrypt('adminPass');
$newUser->firstname = $request->input('tenant_name');
$newUser->lastname = $request->input('tenant_name');
$newUser->email = $request->input('tenant_email');
$newUser->phone = $request->input('tenant_phone');
$newUser->auth_question1 = $newUser->input('auth_question1');
$newUser->auth_answer = $newUser->input('auth_answer');
$newUser->save();
//Attache a the created user to the administrator group
$newUserGroupRelationship = new UserGroupRelationship;
$newUserGroupRelationship->tenant_id = $ewTenant->id;
$newUserGroupRelationship->user_group_id = $newGroup->id;
$newUserGroupRelationship->user_id = $newUser->id;
$newUserGroupRelationship->save();
//Create Profile for the admin user
$newAdministartorProfile = new Profile;
$newAdministartorProfile->tenant_id = $ewTenant->id;
$newAdministartorProfile->name = "Administrator";
$newAdministartorProfile->description = "Created at Tenant creation";
$newAdministartorProfile->save();
//Bind the group to the newly created profile
$newProfileGroupRelationship = new ProfileGroupRelationship;
$newProfileGroupRelationship->tenant_id = $ewTenant->id;
$newProfileGroupRelationship->group_id = $newGroup->id;
$newProfileGroupRelationship->profile_id = $newAdministartorProfile->id;
$newProfileGroupRelationship->save();
//Bind the profile to screen for user access
return response()->json(["success"=>true,'error'=> '']);
//Commit transaction
DB::commit();
return response()->json(["success"=>true]);
}
catch(\Exception $ex)
{
DB::rollback();
return response()->json(["error"=>"cant create tenant at this time","errormessage"=>$ex]);
}
如何将所有这些放在一个交易中? 感谢。
答案 0 :(得分:0)
作为结束的一部分,你应该传递DB::transaction(function()use($request){
// Code goes here to insert and update models.
})
。像:
{{1}}