wildside / userstamps
Laravel Userstamps 提供了一个 Eloquent 特性,该特性可以自动在您的模型上维护 `created_by` 和 `updated_by` 列,并由您的应用程序中当前认证的用户填充。
Requires
- php: >=5.5.9
- illuminate/support: ^5.2|^6.0|^7.0|^8.0|^9.0|^10.0|^11.0
Requires (Dev)
- illuminate/database: ^5.2|^6.0|^7.0|^8.0|^9.0|^10.0|^11.0
- orchestra/testbench: ^3.1|^4.0|^5.0|^6.0|^7.0|^8.0|^9.0
- phpunit/phpunit: ^5.0|^6.0|^7.0|^8.4|^9.0|^10.0
README
关于 Laravel Userstamps
Laravel Userstamps 提供了一个 Eloquent 特性,该特性可以自动在您的模型上维护 created_by
和 updated_by
列,并由您的应用程序中当前认证的用户填充。
当使用 Laravel SoftDeletes
特性时,此包也会处理 deleted_by
列。
安装
此包需要 Laravel 5.2 或更高版本,且运行在 PHP 5.6 或更高版本上。
可以使用 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 许可证 许可。