kyleboehlen/eloquent-uuid

为Laravel Eloquent模型添加和使用uuid的特性和更新至Laravel 9的模型

2.0.0 2022-04-01 03:14 UTC

This package is auto-updated.

Last update: 2024-09-29 06:14:42 UTC


README

Packagist Packagist Packagist Buy us a tree

为Laravel Eloquent模型添加和使用uuid的特性和更新至Laravel 9的模型。

该特性能监听creating事件。它会生成一个新的UUID并将其保存在模型的uuid列中。

被收录在 Laravel News

原始包已不再维护,这个分支已更新以兼容Laravel 8.0和Laravel 9.0,其中laravel/framework替代了illuminate/support

作者建议的包不能直接替换这个特性,所以这个分支是为更新后的Laravel版本准备的。

安装

composer require kyleboehlen/eloquent-uuid

使用

要在模型中使用这个特性,只需添加use HasUuidTrait;

<?php

namespace App;

use KyleBoehlen\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被注册为Route Key使用隐式绑定[https://laravel.net.cn/docs/9.x/routing#implicit-binding],资源控制器将使用uuid而不是默认的id列。

<?php

    php artisan make:controller UserController --resource

/users/{user} 路由使用 uuid,即 /users/bff37872-1450-47c7-b9f7-9a6d917796cf

您还可以使用查询构建器的withUuidwithUuids局部查询作用域。

<?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森林做出贡献,您将为当地家庭创造就业机会,并恢复野生动物栖息地。