xt / laravel-userstimetamps
Laravel Userstamps 提供了一个 Eloquent 特性,它可以自动在你的模型上维护 `created_by` 和 `updated_by` 列,这些列由应用程序中当前认证的用户填充。
Requires
- php: >=5.5.9
- illuminate/support: ^5.2|^6.0|^7.0|^8.0
Requires (Dev)
- illuminate/database: ^5.2|^6.0|^7.0|^8.0
- orchestra/testbench: ^3.1|^4.0|^5.0
- phpunit/phpunit: ^5.0|^6.0|^7.0|^8.4|^9.0
README
关于 Laravel Userstamps
Laravel Userstamps 提供了一个 Eloquent 特性,它可以自动在你的模型上维护 created_by
和 updated_by
列,这些列由应用程序中当前认证的用户填充。
当使用 Laravel 的 SoftDeletes
特性时,此包还会处理 deleted_by
列。
安装
此包需要 Laravel 5.2 或更高版本,运行在 PHP 5.6 或更高版本的 PHP 上。
可以使用 composer 安装此包
composer require wildside/userstamps
使用
您的模型需要包含一个 created_by
和 updated_by
列,默认为 null
。
如果使用 Laravel 的 SoftDeletes
特性,它还需要一个 deleted_by
列。
列类型应与用户表中 ID 列的类型匹配。在 Laravel <= 5.7 中,此值默认为 unsignedInteger
。对于 Laravel >= 5.8,此值默认为 unsignedBigInteger
。
示例迁移
$table->unsignedBigInteger('created_by')->nullable(); $table->unsignedBigInteger('updated_by')->nullable();
现在您可以在模型中加载此特性,Userstamps 将自动维护
use Wildside\Userstamps\Userstamps; class Foo extends Model { use Userstamps; }
可选地,如果您想覆盖 created_by
、updated_by
或 deleted_by
列的名称,您可以在模型上设置相应的类常量。请确保在迁移中匹配这些列名。
use Wildside\Userstamps\Userstamps; class Foo extends Model { use Userstamps; const CREATED_BY = 'alt_created_by'; const UPDATED_BY = 'alt_updated_by'; const DELETED_BY = 'alt_deleted_by'; }
使用此特性时,还提供了辅助关系,以便您可以检索创建、更新和删除(当使用 Laravel 的 SoftDeletes
特性)您的模型的用户。
$model->creator; // the user who created the model $model->editor; // the user who last updated the model $model->destroyer; // the user who deleted the model
还提供了方法,可以暂时停止在您的模型上自动维护 userstamps
$model->stopUserstamping(); // stops userstamps being maintained on the model $model->startUserstamping(); // resumes userstamps being maintained on the model
解决方案
此包通过挂钩到 Eloquent 的模型事件监听器来工作,并受所有此类监听器的限制。
当您对绕过 Eloquent 的模型进行更改时,事件监听器不会被触发,userstamps 也不会更新。
通常这会在批量更新或删除模型及其关系时发生。
在这个例子中,模型关系通过 Eloquent 更新,Userstamps 将会维护
$model->foos->each(function ($item) { $item->bar = 'x'; $item->save(); });
然而,在这个例子中,模型关系批量更新并绕过了 Eloquent。Userstamps 不会维护
$model->foos()->update([ 'bar' => 'x', ]);
作为对此问题的解决方案,提供了两个辅助方法 - updateWithUserstamps
和 deleteWithUserstamps
。它们的行为与 update
和 delete
相同,但确保在模型上维护 updated_by
和 deleted_by
属性。
通常您不需要使用这些方法,除非进行绕过 Eloquent 事件的批量更新。
在这个例子中,模型批量更新且 Userstamps 不会维护
$model->where('name', 'foo')->update([ 'name' => 'bar', ]);
然而,在这个例子中,使用辅助方法批量更新模型,Userstamps 将会维护
$model->where('name', 'foo')->updateWithUserstamps([ 'name' => 'bar', ]);
赞助商
此开源软件由 WILDSIDE 开发和维护。
许可协议
此开源软件根据 MIT 许可协议 许可。