Laravel DB::transaction没有使用模型事件捕获Exception


Laravel DB::transaction doesnt catch the Exception using model events

我是Laravel的新手,我正在尝试处理Model事件。假设一个模型有以下事件(注意手动抛出的异常)

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::transaction Doesnt捕捉不到Model抛出的Exception,因此我无法回滚该事务。

我做错什么了吗??

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

它按预期工作。问题是,您在将新条目包装到事务中之前先创建它。

 $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());
 });