limanweb / eloquent-extensions
Laravel Eloquent\Model 扩展
v1.2.1
2024-05-28 17:56 UTC
Requires
- php: ^7.2|^8.0
This package is auto-updated.
Last update: 2024-09-28 18:42:36 UTC
README
Laravel Eloquent\Model 和其他类别的扩展
- 特性 HasUserstamps 用于通过授权用户ID填充用户戳字段
created_at、updated_at、deleted_at
安装
运行
composer require "limanweb/eloquent-extension"
包内容
- /模型
- /关注点
- HasUsertimestamps.php - 用于模型中填充用户戳特性的 trait
- HasCompositePrimaryKey.php - 用于模型复合主键的 trait
- HasBuilderConfigurator - 用于构建带有请求参数的查询的 trait 草稿
- /关注点
用法
HasUserstamps
将用户戳字段 created_at、updated_at 和 deleted_at 添加到创建或更新表的迁移字段中。例如修改 CreateUsersTable 迁移。
class CreateUsersTable extends Migration { public function up() { Schema::create('users', function (Blueprint $table) { ... // add userstamps fields $table->bigInteger('created_by')->nullable(); $table->bigInteger('updated_by')->nullable(); // if SoftDeletes trait will be used in model then add deleted_by field // $table->bigInteger('deleted_by')->nullable(); }); } ... }
在模型中必须
- 声明使用 trait Limanweb\EloquentExt\Models\Concerns\HasUserstamps
- 在模型中使用 HasUserstamps 特性
- 通过将公共属性
$userstamps定义为true来启用用户戳
... use Limanweb\EloquentExt\Models\Concerns\HasUserstamps; // (1) declare class User extends Authenticatable { use Notifiable; use HasUserstamps; // (2) use trait in the model public $userstamps = true; // (3) enable userstamps ... }
当您创建和更新模型时,模型中的 created_by 和 updated_by 字段将按与时间戳字段相同的方式填充。如果您的模型使用 SoftDeletes 特性,则也会处理字段 deleted_by。
HasCompositePrimaryKey
在模型中必须
- 声明使用 trait Limanweb\EloquentExt\Models\Concerns\HasCompositePrimaryKey
- 在模型中使用 HasCompositePrimaryKey 特性
- 将模型属性 $incrementing 设置为
false - 将模型属性 $primaryKey 设置为数组形式的复杂主键部分名称
... use Limanweb\EloquentExt\Models\Concerns\HasCompositePrimaryKey; // (1) declare trait class Example extends Model { use HasCompositePrimaryKey; // (2) use trait in the model public $incrementing = false; // (3) protected $primaryKey = ['part1', 'part2']; // (4) ... }
使用示例
>>> $m = Example::find([65, 275]); => App\Example {#3837 part1: 65, part2: 275, message: "record 65:275", } >>> $m->getKey(); => [ 65, 275, ]