laravel - laravel 数据库更新获取更改列
问题描述
当我更新数据库上的内容时,我想保存更改日志。有一种优雅的方式来获取将要更新的列(只要有变化)。我想在日志中保存旧列值..
例如:
$updateUser = DB::table('users')->where('id','1')->update(array('email' => 'new@email.com', 'name' => 'my new name'));
从此我想取回旧电子邮件在数据库中(如果更改)和旧名称(再次,仅在更改时)
谢谢!
解决方案
正如其他人所提到的,如果使用 Laravel,Eloquent 是一个很好的选择。然后你可以使用 Observers 直接访问 Laravel 的事件。我使用了一种与下面非常相似的方法。当然,您需要为User和AuditLog设置模型。
查看有关观察者的更多信息。
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,
]);
}
}
}
}
我希望这有帮助!
编辑:请参阅有关更新的评论。
推荐阅读
- python-3.x - Python pandas,如何用在另一个数据框中查找的值替换数据框 NA 值?
- google-cloud-platform - 仅将某些文件移动到 GCP 并保留子文件夹
- blazor - 在 Blazor 客户端和 Blazor 服务器之间存储和检索数据
- html - 当我将它放在 Html 脚本标签中并通过浏览器打开 html 时,React 包不起作用
- linux - bash检查文件中的所有行是否等于“数字”
- java - 如何在 BOX Api 中上传文件:空指针异常
- c++ - Vowpal Wabbit 是否支持在训练期间添加和删除功能?
- spring - Bean 名称错误的 BindingResult 和普通目标对象都不是
- swift - 如何衡量异步方法的性能?
- html - CSS 样式表适用于某些属性,但不是全部