首页 > 解决方案 > laravel 数据库更新获取更改列

问题描述

当我更新数据库上的内容时,我想保存更改日志。有一种优雅的方式来获取将要更新的列(只要有变化)。我想在日志中保存旧列值..

例如:

$updateUser = DB::table('users')->where('id','1')->update(array('email' => 'new@email.com', 'name' => 'my new name'));

从此我想取回旧电子邮件在数据库中(如果更改)和旧名称(再次,仅在更改时)

谢谢!

标签: laravel

解决方案


正如其他人所提到的,如果使用 Laravel,Eloquent 是一个很好的选择。然后你可以使用 Observers 直接访问 Laravel 的事件。我使用了一种与下面非常相似的方法。当然,您需要为UserAuditLog设置模型。

查看有关观察者的更多信息。
https://laravel.com/docs/5.8/eloquent#observers

在控制器方法中

$user = User::find(1);
$user->update([
    'email' => 'new@email.com',
    'name' => 'my new name'
]);

应用程序/提供者/EventServiceProvider.php

class EventServiceProvider extends ServiceProvider
{
    // ...

    public function boot()
    {
        User::observe(UserObserver::class);
    }
}

应用程序/观察者/UserObserver.php

class UserObserver
{
    /**
     * The attributes to exclude from logging.
     *
     * @var array
     */
    protected $except = [
        'created_at',
        'updated_at'
    ];

    /**
     * The attributes to mask.
     *
     * @var array
     */
    protected $masked = [
        'password',
    ];

    /**
     * Listen for model saved event.
     *
     * @var array
     */
    public function saved($model)
    {
        // search for changes
        foreach ($model->getChanges() as $key => $new_value) {

            // get original value
            $old_value = $model->getOriginal($key);

            // skip type NULL with empty fields
            if ($old_value === '' && $new_value === null) {
                continue;
            }

            // attribute not excluded and values are different
            if (!in_array($key, $this->except) && $new_value !== $old_value) {

                // mask designated fields
                if (in_array($key, $this->masked)) {
                    $old_value = '********';
                    $new_value = '********';
                }

                // create audit log
                AuditLog::create([
                    'user_id' => auth()->user()->id,
                    'model_id' => $model->id,
                    'model' => (new \ReflectionClass($model))->getShortName(),
                    'action' => 'update',
                    'environment' => config('app.env'),                   
                    'attribute' => $key,
                    'old_value' => $old_value,
                    'new_value' => $new_value,
                ]);
            }
        }
    }
}

我希望这有帮助!

编辑:请参阅有关更新的评论。


推荐阅读