首页 > 解决方案 > 事务 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;
    }
}

标签: mysqllaraveltransactions

解决方案


您可以像下面这样非常容易地添加您的交易,只需添加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');
}

推荐阅读