多次和关联雄辩的回滚事务

时间:2019-10-17 04:10:19

标签: php laravel http

所以我遇到了问题,因为在控制器上的存储功能中,我正在执行2次(或更多次)创建,而第二次创建则依赖于第一个创建ID,当我的第二个创建失败时,它将返回异常,但第一个创建已经已经完成,并且因为我的第一个创建操作具有唯一的验证规则,下次用户在前端单击保存按钮时,由于重复输入,它将显示错误。

在我的控制器中看起来像这样

public function store(Request $request)
{
    try{
        $this->validate($request,Seller::$rules);

        $name = $request->name;

        if(!empty($request->gambar))
            $fileName = Helper::image_processing($this->imagepath,$this->width,$this->height,$request,'');
        else
            $fileName = ''; 

        // my first create
        $class = Seller::create($request->except('gambar') + [
            'gambar' => $fileName
        ]);

        // my second create that depends on first create id
        $this->syncProduct($request, $class->id);

        return response()
            ->json([
                'saved' => true,
                'message' => $this->message. ' ' .$name. ' already been added',
                'id' => $class->id
            ]); 
    } catch (\Exception $e){
        $errorCode = $e->errorInfo[1];
        if($errorCode == 1062){
            abort(500, 'Duplicate seller id');
        }else{
            abort(500, $e->getMessage());
        }
    }
}

我的问题是如何具有某种回滚功能,如果其中发生任何错误,它将回溯到创建/更新任何数据之前?

1 个答案:

答案 0 :(得分:1)

您可以使用\DB::beginTransaction()进行交易。要提交\DB::commit();,并且如果从catch中获取任何错误,则可以像此\DB::rollBack();那样回滚。

// Begin Transaction
\DB::beginTransaction(); 
    try {
       //your code.
       // Commit Transaction
        \DB::commit();

    } catch (\Illuminate\Database\QueryException $ex) {
        $msg = $ex->getMessage();
        if (isset($ex->errorInfo[2])) :
            $msg = $ex->errorInfo[2];
        endif;
        // Rollback Transaction
        \DB::rollBack();
        $arr = array("status" => 400, "msg" =>$msg, "result" => array());
    } catch (Exception $ex) {
        $msg = $ex->getMessage();
        if (isset($ex->errorInfo[2])) :
            $msg = $ex->errorInfo[2];
        endif;
        // Rollback Transaction
        \DB::rollBack();
        $arr = array("status" => 400, "msg" =>$msg, "result" => array());

   }