laragrad / eloquent-model-userstamps
Requires
- php: ^7.2|^8.0
This package is auto-updated.
Last update: 2024-09-23 22:40:19 UTC
README
本包为模型提供了一个特性,用于填充用户戳字段。
安装
在控制台运行命令
composer require laragrad/eloquent-model-userstamps
使用
准备表
将用户戳字段添加到模型表的迁移文件中。其类型必须与用户ID的类型相同。您可以使用默认的 created_by、updated_by、deleted_by 字段名或任何其他名称。
您可以使用 Laragrad\Support\Userstamps 的 addUserstampColumns() 方法在迁移文件中添加或 dropUserstampColumns() 删除列。
例如,要添加用户戳列
<?php
use ...;
use Laragrad\Support\Userstamps as UserstampsSupport; // Add use
class CreateExampleTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('examples', function (Blueprint $table) {
$table->id('id');
...
UserstampsSupport::addUserstampsColumns($table); // Creating columns
});
}
...
}
如果您在表中使用软删除,则在第二个参数中放入 true。要更改用户戳列的类型,您可以在第三个参数中放入 'uuid'、'integer' 或 'bigInteger'。默认创建的列具有默认名称。如果您的用户戳列没有默认名称,则将列名数组放入第四个参数。
例如
UserstampsSupport::addUserstampsColumns($table, true, 'uuid', ['create_user_id','update_user_id','deleted_user_id']);
要删除列,您可以使用 UserstampsSupport::dropUserstampsColumns()。例如
UserstampsSupport::dropUserstampsColumns($table, true, ['create_user_id','update_user_id','deleted_user_id']);
准备模型
将以下更改添加到您的表模型类中
-
在您的模型类中添加使用特性
\Laragrad\Models\Concerns\HasUserstamps; -
添加属性
public $userstamps = true;use Laragrad\Models\Concerns\HasUserstamps; // (1)
class YourModel extends Model { use HasUserstamps; // (2)
public $userstamps = true; // (3) ...}
现在,在创建或更新模型时,您的模型中的 created_by 和 updated_by 字段将像时间戳字段一样填充。如果您的模型使用 SoftDeletes 特性,deleted_by 字段也将被处理。
使用自定义用户戳字段名
如果您的表用户戳字段名不是默认的,则请在您的模型中声明以下常量
class YourModel extends Model
{
...
const CREATED_BY = 'your_created_by_field_name';
const UPDATED_BY = 'your_updated_by_field_name';
const DELETED_BY = 'your_deleted_by_field_name';
...
}