jamesmills/eloquent-uuid

此包已被弃用且不再维护。作者建议使用dyrynda/laravel-model-uuid包。

用于为模型添加和使用uuid的Laravel Eloquent模型特性

安装量: 43,101

依赖项: 0

建议者: 0

安全性: 0

星标: 139

关注者: 7

分支: 15

开放问题: 6

类型:package

1.6.1 2020-09-23 15:33 UTC

This package is auto-updated.

Last update: 2022-02-14 03:52:47 UTC


README

Packagist Packagist Packagist Buy us a tree

为模型添加和使用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

你也可以使用查询构建器的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森林做出贡献,你将为当地家庭创造就业机会并恢复野生动物栖息地。