【问题标题】:Laravel DB::transaction doesnt catch the Exception using model eventsLaravel DB::transaction 没有使用模型事件捕获异常
【发布时间】:2014-11-16 13:38:39
【问题描述】:

我对 Laravel 还很陌生,我正在尝试使用模型事件。 考虑一个模型有这些事件(注意手动抛出的异常)

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');
    }
}

Controller 的 store 方法:

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 没有捕捉到模型抛出的异常,所以我无法回滚事务。

我是不是做错了什么??

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

【问题讨论】:

    标签: php laravel transactions


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-16
      • 1970-01-01
      • 2015-05-30
      • 2023-04-04
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      相关资源
      最近更新 更多