jamesmills / eloquent-uuid
1.6.1
2020-09-23 15:33 UTC
Requires
- php: >=7.2.0
- illuminate/support: 5.4.* || 5.5.* || 5.6.*|| 5.7.*|| 5.8.*|| ^6 || ^7 || ^8
- ramsey/uuid: ^4.1
README
为模型添加和使用uuid的Laravel Eloquent模型特性。
特性监听creating
事件。它生成一个新的UUID并将其保存到模型的uuid列。
在Laravel News中展示
安装
composer require jamesmills/eloquent-uuid
使用
为了在你的模型中使用此特性,只需添加use HasUuidTrait;
<?php namespace App; use JamesMills\Uuid\HasUuidTrait; class User extends Eloquent { use HasUuidTrait; }
模式要求
为了使用此特性,你的模式必须是类似以下的形式
<?php // ... Schema::create('users', function (Blueprint $table) { $table->primary('id'); $table->uuid('uuid')->unique(); // this will create a CHAR(36) field $table->string('username', 32); $table->string('password', 50); // ... });
查询你的模型
你可以使用findByUuidOrFail
方法来尝试直接获取一个模型
<?php Route::get('/user/{uuid}', function($uuid) { try { return App\User::findByUuidOrFail($uuid); } catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) { abort(404); } });
由于uuid
通过隐式绑定[https://laravel.net.cn/docs/5.8/routing#implicit-binding]注册为路由键,所以你的资源控制器将使用uuid
而不是默认的id
列。
<?php php artisan make:controller UserController --resource
/users/{user}路由使用uuid
,即/users/bff37872-1450-47c7-b9f7-9a6d917796cf
你也可以使用查询构建器的withUuid
和withUuids
局部查询范围。
<?php Route::get('/user/{uuid}', function($uuid) { $user = App\User::withUuid($uuid)->first(); if (! $user) { // Do something else... } });
<?php Route::delete('/users', function(Request $request) { // Receive an array of UUIDs $uuids = $request->input('uuids'); // Try to get the Users $users = App\User::withUuids($uuids)->all(); // Handle the delete and return $users->delete(); });
许可证
此包是100%免费和开源的,受MIT许可证保护。你可以随意使用它。
此包是Treeware。如果你在生产环境中使用它,我们要求你为我们买一棵树以感谢我们的工作。通过为Treeware森林做出贡献,你将为当地家庭创造就业机会并恢复野生动物栖息地。