模型事件未触发

时间:2015-11-18 13:27:21

标签: php laravel-4

我在Post模型中有以下代码。触发created事件,但updated不是。

我正在更新模型:

Post::where('key','=','some_key_goes_here')->first()->fill(['status' => 'approved'])->save();

我的模型看起来像这样:

public function Post extends \Eloquent {
    public static function boot()
    {
        parent::boot();

        Post::created(function ($model) {
            Queue::push('\MyApp\Jobs\Notifications\sendNotification', [
                'id' => $model->user_id,
                'key' => $model->key,
                'status' => $model->status
            ]);
        });

        Post::updated(function ($model) {
            //if the status has changed
            $statusChanged = false;
            foreach ($model->getDirty() as $attribute => $value) {
                if ($attribute == 'status' && $model->getOriginal($attribute) != $value) {
                    $statusChanged = true;
                }
            }

            if ($statusChanged) {
                Notification::add($model->key, $model->status);
            }
        });
    }
}

1 个答案:

答案 0 :(得分:2)

更新的+ getOriginal第二个参数的简短版本作为可能的修复。

Post::updated(function ($model) {
    //if the status has changed
    foreach ($model->getDirty() as $attribute => $value) {
        if ($attribute == 'status' && $model->getOriginal($attribute, $value) != $value) {
            Notification::add($model->key, $model->status);
            break;
        }
    }
});