php - Eloquent:在模型和他的 parent 身上 Hook 到 'saving' 事件

标签 php laravel eloquent

有这个 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 or 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
        });
    }
}

关于php - Eloquent:在模型和他的 parent 身上 Hook 到 'saving' 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29778912/

相关文章:

php - 如何在 Laravel 上以良好的实践方式处理 undefined variable 和数组

php - Laravel 查询比较数据库中的两个字符串,日期格式为 Y-m

mysql - 违反完整性约束 : 1052 Column and in where clause is ambiguous

php - Eloquent Tinker - 未定义常量

laravel - 为什么我们需要像Pusher、Socket.io这样的产品来建立websocket连接?

php - Phalcon, IIS, 重写

php - 下面的 SQL Select 语句 < 运算符不起作用

php - CRM应用程序的数据库表结构

PHP MYSQL 选择邮政编码或客户 ID 或其他任何内容

Laravel 与 Bootstrap 4 的混合