touhidurabir / laravel-model-uuid
一个Laravel包,用于将UUID附加到模型类
Requires
- ramsey/uuid: ^4.2
Requires (Dev)
- illuminate/container: ^8.54
- illuminate/database: ^8.54
- illuminate/events: ^8.54
- illuminate/support: ^8.54
- orchestra/testbench: ^6.20
- phpunit/phpunit: ^9.5
README
一个用于为Laravel模型生成简单UUID的包
安装
使用Composer安装包
composer require touhidurabir/laravel-model-uuid
发布配置文件
php artisan vendor:publish --provider="Touhidurabir\ModelUuid\ModelUuidServiceProvider" --tag=config
使用方法
在需要附加UUID的模型中使用强类型HasUuid
use Touhidurabir\ModelUuid\HasUuid; use Illuminate\Database\Eloquent\Model; class User extends Model { use HasUuid; }
默认情况下,此包使用列名uuid来附加UUID并在模型创建
事件上执行。但这些配置可以从model-uuid.php
配置文件中更改。
也可以从每个模型中覆盖UUID列和附加事件。为此,需要在模型中放置以下方法
use Touhidurabir\ModelUuid\HasUuid; use Illuminate\Database\Eloquent\Model; class User extends Model { use HasUuid; public function uuidable() : array { return [ 'column' => 'uuid', 'event' => 'created', ]; } }
确保在迁移文件中放置UUID列名
$table->string('uuid')->nullable()->unique()->index();
或者可以与模型-UUID配置结合使用,如下所示
$table->string(config('model-uuid.column'))->nullable()->unique()->index();
此包还包括一些辅助方法,可以轻松通过UUID查找模型记录。例如
User::byUuid($uuid)->where('active', true)->first(); // single uuid User::byUuid([$uuid1, $uuid2])->where('active', true)->get(); // multiple uuid
或者简单直接地查找
User::findByUuid($uuid); // single uuid User::findByUuid([$uuid1, $uuid2]); // multiple uuid
此包还提供了一些保护措施,通过检查模型表是否有给定的UUID列。
如果模型表架构中找不到UUID列,则不会创建和附加UUID。
也可以通过使用提供的静态
方法暂时禁用特定目的的UUID生成。然后可以再次启用。
User::disbaleUuidGeneration(true) // this will diable uuid generation temporarily for model User::disbaleUuidGeneration(false) // this will enable uuid generation for model again
命令
此包包含一个命令,可用于为缺少UUID的模型设置UUID或更新现有的UUID。如果此包在包含一些数据的任何Laravel应用程序中之后使用,并且需要为这些记录设置UUID,这将非常有用。要使用此命令运行
php artisan uuid:regenerate User,Profile
该命令需要一个参数
,即模型命令的名称(如果有多个模型要运行,请分开)。
--path=
默认情况下,它假定所有模型都位于App\Models\
命名空间中。但如果它们位于其他位置,请使用此选项定义正确的模型空间路径,并带有尾部斜杠
。
--update-all
默认情况下,此命令仅适用于具有定义的UUID列null的模型记录。因此,基本上它将填充缺失的记录,但如果此选项与命令一起提供,则无论UUID是否关联,它都将更新所有记录。
--on-job
此定义是否将通过队列工作更新/填充缺失的记录。命令使用一个工作,其中主要逻辑位于。但默认情况下,它使用框架提供的dispatchNow
方法以同步方式运行作业。如果提供了标志并且队列配置正确,则它将作业推入队列。
--job=
如果需要传递自定义队列工作实现,则可以直接通过此选项提供。还可以在配置文件中更新队列类。
默认作业在配置文件
model-uuid
中定义为键regeneration_job
。
贡献
欢迎拉取请求。对于主要更改,请首先打开一个问题来讨论您想要更改的内容。
请确保根据需要更新测试。