Laravel 4中的模型观察者,restore()触发recover()和updated()

时间:2015-04-08 10:58:46

标签: php laravel-4

我在Laravel 4中的模型上使用观察者来保存每个用户所做更改的历史记录。我目前使用的代码如下:

class BaseObserver {

    public function __construct(){}

    public function saving(Eloquent $model){}

    public function saved(Eloquent $model){}

    public function updating(Eloquent $model){}

    public function updated(Eloquent $model)
    {
        $this->storeAuditData($model, 'update');
    }

    public function creating(Eloquent $model){}

    public function created(Eloquent $model)
    {
         $this->storeAuditData($model, 'create');
    }

    public function deleting(Eloquent $model){}

    public function deleted(Eloquent $model)
    {
        $this->storeAuditData($model, 'delete');
    }

    public function restoring(Eloquent $model){}

    public function restored(Eloquent $model)
    {
         $this->storeAuditData($model, 'restore');
    }

    public function storeAuditData(Eloquent $model, $action)
    {
        $snapshot = array();
        foreach ($model->fillable as $fieldName) {
            $snapshot[$fieldName] = $model->$fieldName;
        }

        $auditData = new AuditData;
        $auditData->model = get_class($model);
        $auditData->rowId = $model->id;
        $auditData->action = $action;
        $auditData->user = Auth::user()->username;
        $auditData->moment = date('Y-m-d H:i:s');
        $auditData->snapshot = json_encode($snapshot);
        $auditData->save();

    }

}

这样可以正常工作,除非执行 restore()恢复的更新的方法都会运行,所以我最终在AuditData数据库表中有两行,当我只需要一行时(“恢复”)。

我是否可以在更新的方法中判断更新是否为还原,如果审核数据是独立更新而不是还原,则只存储审核数据?< / p>

2 个答案:

答案 0 :(得分:1)

您可以检查是否只修改了deleted_at列(

public function updated(Eloquent $model)
{
    if($model->isDirty($model->getDeletedAtColumn()) && count($model->getDirty()) == 1){
        // only soft deleting column changed
    }
    else {
        $this->storeAuditData($model, 'update');
    }
}

答案 1 :(得分:0)

在恢复和使用 Laravel 自动时间戳时,列 updated_at 将与 deleted_at 一起修改。为了区分“已恢复”和“已更新”观察者事件,在我使用的 updated 方法中:

public function updated(Eloquent $model)
{
    if ($model->isDirty($model->getDeletedAtColumn())
        && $model->{$model->getDeletedAtColumn()} === null
        && $model->getOriginal($model->getDeletedAtColumn()) !== null) {

        // model was restored
    }
}