phumsoft / userstamps
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|^6.0
- phpunit/phpunit: ^5.0|^6.0|^7.0|^8.4|^9.0
This package is auto-updated.
Last update: 2024-09-25 14:05:30 UTC
README
关于Laravel Userstamps
Laravel Userstamps提供了一种Eloquent特质,可以自动在您的模型上维护created_by
和updated_by
列,并由您应用程序中当前认证的用户填充。
当使用Laravel SoftDeletes
特质时,此包还会处理deleted_by
列。
安装
此包需要Laravel 5.2或更高版本,并在PHP 5.6或更高版本上运行。
您可以使用composer安装此包
composer require Phumsoft/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 Phumsoft\Userstamps\Userstamps; class Foo extends Model { use Userstamps; }
可选地,如果您希望覆盖created_by
、updated_by
或deleted_by
列的名称,您可以在模型上设置相应的类常量。确保您在迁移中匹配这些列名。
use Phumsoft\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', ]);
许可
此开源软件许可协议为MIT许可。