1

我已经将 Larvel 5.0 与数据库事务一起使用,所有方法在我之前的 Web 应用程序中都可以正常工作,我们真的很喜欢它,因为这个应用程序对我的帮助比我们估计的要多得多

所以我们使用这个框架的最新版本创建了另一个 web 应用程序,并使用了相同的数据库结构,但最终它对我和另一个人都不起作用。我有更多的人,并在一些旅游网站上发帖询问任何问题,但还没有得到任何解决方案,所以我录制了这个视频来确定这个案例。

问题:我的问题我已禁用 (//commit()) 方法,所有数据仍然可以插入数据库。

 final function Add()
    {
        if ($this->request->isMethod('post')) {

            //No you will see this method use with Try Catch and testing again
            //DB::beginTransaction(); // Ihave testing with outside of try and inside again

            Try{

                DB::beginTransaction();

                $cats = new Cat();
                $catD = new CategoryDescriptions();

                $cats->parent_id = $this->request->input('category_id');
                $cats->status = ($this->request->input('status')) ? $this->request->input('status') : 0;
                if (($res['result'] = $cats->save())== true) {

                    $catD->category_id = $cats->id;
                    $catD->language_id = 1;
                    $catD->name = $this->request->input('en_name');
                    if (($res['result'] = $catD->save()) === true) {

                        $catD2 = new CategoryDescriptions();
                        $catD2->category_id = $cats->id;
                        $catD2->language_id = 2;
                        $catD2->name = $this->request->input('kh_name');
                        $res['result'] = $catD2->save();
                    }
                }
                if(!empty($res)) {
                    //DB::commit();
                }
                return [$res,($res['result'] = $catD->save())];
            }catch(\Exception $e){ // I have already try to use Exception $e without backslash
                DB::rollback();
            }
        }

        $cat = Cat::with(['CategoryDescriptions', 'children'])->where('status', 1)->get();

        return view('admin.categories.add', ['cat' => $cat]);
    }

你可以看看我的视频看看。

看看我的视频

4

1 回答 1

1

我不知道为什么你的代码不起作用。但是您可以尝试使用此代码,我认为它会起作用。 Laravel 交易文档

try{
     DB::transaction(function)use(/*your variables*/){

       // your code
   });
 }catch(\PDOException $exception){
    //debug
}

如果发生任何异常,它将自动回滚。如果你想手动回滚,那么在事务内部你可以根据你的逻辑抛出一个手动异常。

于 2017-01-16T03:33:57.560 回答