laravel - 如何捕获数据透视表中的模型事件

标签 laravel laravel-4 model eloquent

我想跟踪(记录)对每个数据库行所做的更改。这意味着,保存对每个表的每条记录进行的每个操作(插入、更新、删除)的日志。

此问题已针对模型得到解决,因为它们是从 BaseModel 扩展而来的,而我正在使用 model events 。但是,我似乎找不到一种方法来记录数据透视表的更改。

鉴于下表usersprofilesprofile_user(profile_id, user_id),我有以下代码:

class User extends BaseModel {
    public function profiles() {
        return $this->belongsToMany('Profile');
    }
}

class Profile extends BaseModel {
    public function users() {
        return $this->belongsToMany('User');
    }
}

abstract class BaseModel extends Model {
    public static function boot() {
        parent::boot();

        static::created(function($model) {
            return LogTracker::saveRowCreatedOrUpdated($model, true);
        });

        static::updated(function($model) {
            return LogTracker::saveRowCreatedOrUpdated($model, false);
        });

        static::deleted(function($model) {
            return LogTracker::saveRowDeleted($model);
        });
    }
}

这使我能够记录 userprofile 的更改,但不能记录 profile_user 的更改。

我尝试创建一个从 Pivot (Illuminate\Database\Eloquent\Relations\Pivot) 扩展的 ProfileUser 模型,我在其中定义了模型事件,但这不起作用。

我猜这是因为我从未创建过该模型的新实例。因此,我将以下内容添加到我的 User 模型中(以及与 Profile 类似的代码):

class User extends BaseModel {
    // (...)
    public function newPivot(Eloquent $parent, array $attributes, $table, $exists) {
        if ($parent instanceof Profile) {
            return new ProfileUser($parent, $attributes, $table, $exists);
        }
        return parent::newPivot($parent, $attributes, $table, $exists);
    }
    // (...)
}

尽管如此,事件永远不会被触发(实际上这个方法永远不会被执行)。

我正在通过 sync() 更新关系:

$user->profiles()->sync(explode(',', $values["profiles"]));

我正在寻找一种不涉及触发自定义事件的解决方案(因为这意味着我必须对数据库中的每个数据透视表执行此操作)。

如何在数据透视表中使用模型事件?

最佳答案

我知道您不想要自定义事件情况,但我找不到任何非自定义解决方案。

但是,您可以做一个非常简单的自定义(几乎直接从 Laravel 文档中提取):

DB::listen(function($sql, $bindings, $time)
{
    //regex matching for tables in SQL query
    //as well as firing your event handling code
});

http://laravel.com/docs/4.2/database#running-queries

关于laravel - 如何捕获数据透视表中的模型事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27114870/

相关文章:

php - 在 Laravel 中更新不可填写的字段?

laravel - Eloquent : API Resources vs Fractal

laravel - 路由存在 - 测试认为它不存在

php - 如何防止模型注入(inject)绑定(bind)错误的 uuid?

laravel - Laravel 4 中的自动加载助手

php - Laravel 4 权限

Angular 4 Reactive Form - 显示值

php - Laravel 4 - 连接到其他数据库

ruby-on-rails - Rails_admin 多图片上传?

mysql - 数据库模型的元数据应该在模型文件还是迁移文件中定义?