Eloquent:挂接到模型和他的 parent 上的 'saving' 事件
Eloquent: hook into 'saving' event on both the model and his parent
有这个parent:
class BaseModel extends Eloquent {
protected static $rules = [];
public static function boot() {
parent::boot();
static::saving(function($model) {
return $model->validate(); // <- this executes
});
}
}
我怎样才能在 child 模型上做同样的事情?
class Car extends BaseModel {
protected static $rules = [];
public static function boot() {
parent::boot();
static::saving(function($model) {
$model->doStuff(); // <- this doesn't execute
});
}
}
child 中的 saving()
只有在我删除 parent 上的 saving()
时才会执行。我两个都需要!
我找到了解决办法,其实很简单。
这是 *ing
Eloquent 事件的行为,具体取决于 return 类型:
return null
或no 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
});
}
}
有这个parent:
class BaseModel extends Eloquent {
protected static $rules = [];
public static function boot() {
parent::boot();
static::saving(function($model) {
return $model->validate(); // <- this executes
});
}
}
我怎样才能在 child 模型上做同样的事情?
class Car extends BaseModel {
protected static $rules = [];
public static function boot() {
parent::boot();
static::saving(function($model) {
$model->doStuff(); // <- this doesn't execute
});
}
}
child 中的 saving()
只有在我删除 parent 上的 saving()
时才会执行。我两个都需要!
我找到了解决办法,其实很简单。
这是 *ing
Eloquent 事件的行为,具体取决于 return 类型:
return null
或no 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
});
}
}