mysql - 事务 MYSQL LARAVEL
问题描述
我创建了一个存储方法,它存储了两个将数据保存到不同表的步骤形式。我想要一个场景是,如果任何应该回滚的表的提交失败。
代码
public function store()
{
try{
$staffrecs = Staffrecord::create([
'staff_id' => '',
'first_name' => $this->state['first_name'],
'middle_name' => $this->state['middle_name'],
'last_name' => $this->state['last_name'],
'designation' => $this->state['designation'],
'grade_level_id' => $this->state['grade_level_id'],
'phone_number' => $this->state['phone_number'],
'email' => $this->state['email'],
'address' => $this->state['address'],
]);
$staffrecs->bankaccount()->create([
'account_number' => $this->state['account_number'],
'account_name' => $this->state['account_name'],
'bank_name' => $this->state['bank_name'],
'sort_code' => $this->state['sort_code'],
]);
return redirect()->route('dashboard');
}catch (\Exception $e)
{
return false;
}
}
解决方案
您可以像下面这样非常容易地添加您的交易,只需添加DB::beginTransaction();
beforetry
函数和DB::commit();
after exception
。
public function store()
{
DB::beginTransaction();
try{
$staffrecs = Staffrecord::create([
'staff_id' => '',
'first_name' => $this->state['first_name'],
'middle_name' => $this->state['middle_name'],
'last_name' => $this->state['last_name'],
'designation' => $this->state['designation'],
'grade_level_id' => $this->state['grade_level_id'],
'phone_number' => $this->state['phone_number'],
'email' => $this->state['email'],
'address' => $this->state['address'],
]);
$staffrecs->bankaccount()->create([
'account_number' => $this->state['account_number'],
'account_name' => $this->state['account_name'],
'bank_name' => $this->state['bank_name'],
'sort_code' => $this->state['sort_code'],
]);
}catch (\Exception $e) {
return false;
}
DB::commit();
return redirect()->route('dashboard');
}
推荐阅读
- php - 为什么 api 请求会从 api.php 路由转到 web.php 路由?
- laravel - 将 Vuejs 中的 excel 文件发布到 Laravel
- node.js - “无法读取未定义的属性方法名称”使用具有文档样式的 NodeJS SOAP 方法
- matlab - 在 inputdlg 框中创建下拉菜单
- android - adb卸载不适用于realme设备
- html - 如何在 img 元素上添加径向渐变属性
- reactjs - 下一条路线在嵌套路由中不起作用?
- validation - 访问 - 基于 ID 和日期的验证
- json - 使用 JQ 删除具有某些键值对的父元素
- selenium - ChromeDriver 使用 WebdriverManager for Selenium Protractor 解压缩 85.0.4183.38 版本而不是 84.0.4147.89