2014-09-22 94 views
0

我对Laravel相当陌生,我正在尝试使用Model事件。 考虑一个模型具有这些事件(注意,手动抛出的异常)Laravel DB ::事务不会使用模型事件捕获异常

class Doctor extends \Eloquent { 

    protected $fillable = ['name', 'summary', 'description', 'image']; 

    public static function boot() { 
     parent::boot(); 

     Doctor::deleting(function(Doctor $doctor) { 
      $doctor->page()->delete(); 
     }); 

     Doctor::created(function(Doctor $doctor) { 
      throw new \Exception('hahahah!!!'); 
      $doctor->page()->create(['title' => $doctor->name, 'slug' => $doctor->name]); 
     }); 
    } 

    public function page() { 
     return $this->morphOne('Page', 'pageable'); 
    } 
} 

该控制器的存储方法:

public function store() { 

     // TODO : Extract Validation to a Service. 

     $validator = \Validator::make(
      \Input::only('name'), 
      ['name' => 'required'] 
     ); 
     if ($validator->fails()) { 
      return \Redirect::back()->withErrors($validator)->with(['items' => $this->dataArray]); 
     } 
     $doctor = \Doctor::create(\Input::all()); 

     \DB::transaction(function() use($doctor) { 
      $doctor->save(); 
     }); 

     return \Redirect::route('Emc2.doctors.edit', ['id' => $doctor->id]); 
    } 

的问题是,在DB ::交易犯规赶上抛出异常由模型,所以我不能回滚交易。

我做错了什么?

任何帮助将不胜感激! 谢谢!

回答

2

它按预期工作。问题在于你在交易中包装它之前创建了新的条目。

$doctor = \Doctor::create(\Input::all()); // It already saved the doctor 

\DB::transaction(function() use($doctor) { 
    $doctor->save(); // here you UPDATE doctor 
}); 

所以用这个:

$doctor = new \Doctor(\Input::all()); 

\DB::transaction(function() use($doctor) { 
    $doctor->save(); 
}); 

\DB::transaction(function() use (&$doctor) { 
    $doctor = \Doctor::create(\Input::all()); 
}); 
+0

绝对!多么愚蠢的我:)谢谢! – 2014-09-22 15:17:48