有这个 parent :
class BaseModel extends Eloquent {
protected static $rules = [];
public static function boot() {
parent::boot();
static::saving(function($model) {
return $model->validate(); // <- this executes
});
}
}
我怎样才能在子模型上做同样的事情?
class Car extends BaseModel {
protected static $rules = [];
public static function boot() {
parent::boot();
static::saving(function($model) {
$model->doStuff(); // <- this doesn't execute
});
}
}
仅当我删除父级上的 saving()
时,子级中的 saving()
才会执行。我两个都需要!
最佳答案
我找到了解决方案,其实很简单。
这是 *ing
Eloquent 事件的行为,取决于返回类型:
return null
orno return
:模型将被保存或执行下一个saving
回调return true
:模型将被保存,但下一个saving
回调将NOT被执行return false
:模型不会被保存,下一个saving
回调不会被执行
所以,这个问题的解决方案很简单:
class BaseModel extends Eloquent {
protected static $rules = [];
public static function boot() {
parent::boot();
static::saving(function($model) {
if(!$model->validate())
return false; // only return false if validate() fails, otherwise don't return anything
});
}
}
关于php - Eloquent:在模型和他的 parent 身上 Hook 到 'saving' 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29778912/