Laravel 4:DB :: transaction提供回调以查看结果

Sim*_*ies 1 php transactions laravel laravel-4

我在项目中使用DB :: transaction一切正常,但我首先要做的是创建一个文件夹:

  $folder = \File:: makeDirectory($path, perm, recur);
Run Code Online (Sandbox Code Playgroud)

然后在传递这个i然后初始化我的DB :: transaction:

  if($folder){
    \DB::transaction(function() use($folderName){
        /////--- do the db stuff in here.

   })
  } else {
    ///-- folder creation failed return message
  }
Run Code Online (Sandbox Code Playgroud)

这一切都很好但是如果我的文件夹被创建然后DB ::事务失败,我无法知道这一点,所以我可以删除创建的文件夹,然后通知用户当前进程失败.

任何想法如何我可以获得一个回调类型,以便如果它失败然后删除文件夹,我尝试了尝试捕获,但拉拉斯自己的错误接管,并没有得到那么远?

那怎么能实现这个目标呢?

Ale*_*ult 7

如果事务失败,则抛出异常.你只是抓住它:

$folder = \File:: makeDirectory($path, perm, recur);

if($folder){
  try
  {
    \DB::transaction(function() use($folderName){
      /////--- do the db stuff in here.
    })
  }
  catch (\Exception $e)
  {
    /////--- DB STUFF FAILED

    // TODO: DELETE FOLDER

    throw $e;
  }

} else {
  ///-- folder creation failed return message
}
Run Code Online (Sandbox Code Playgroud)

编辑:参见laravel的源代码:https://github.com/laravel/framework/blob/a4c76fb3601ee75a23dc0aec3f1a7fde86faf91d/src/Illuminate/Database/Connection.php#L415