alsofronie/eloquent-uuid

Laravel Eloquent 模型特质,用于使用 UUID 作为主键

v1.0.9 2017-07-20 18:09 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:36:32 UTC


README

用于 Laravel 5.1 - 5.4 的 Eloquent UUID 特质

MIT licensed Total Downloads

它应该也适用于 Laravel 5.0,但尚未测试。

该特质覆盖了静态 boot 方法并监听 creating 事件。它生成一个 UUID(去除破折号)并将其存储在主键属性中。因此,您需要为模型设置 CHAR(32) 的主键(请参阅下面的迁移)。

安装

composer require alsofronie/eloquent-uuid:dev-master

使用

为了使其更快,您可以选择使用以下三种特质之一

  • UuidModelTrait - 键必须是 CHAR(36) 并包含破折号
  • Uuid32ModelTrait - 键必须是 CHAR(32),破折号将被去除
  • UuidBinaryModelTrait - 键是 BINARY(16)

使用 UuidModelTrait

为了使用此特质,您的 模式 必须类似于

<?php
	// ...
	Schema::create('users', function (Blueprint $table) {
		$table->uuid('id');	// this will create a CHAR(36) field
		// or
		// $table->char('id', 36);
		$table->string('username', 32);
		$table->string('password', 50);
		// ...
		$table->primary('id');
	});

使用 Uuid32ModelTrait

对于此类型,只需在您的模式中使用 CHAR(32)(这与第一个类似,但去除了破折号)。

<?php
	// ...
	Schema::create('users', function (Blueprint $table) {
		$table->char('id', 32);
		// ...
		$table->string('username', 32);
		$table->string('password', 50);

		$table->primary('id');
	});

使用 UuidBinaryModelTrait

这将以二进制格式存储键。默认的 Laravel Blueprint 当前 不支持指定长度的二进制字段,并且在(至少在 MySQL 中)您无法在 BINARY 字段(包括主键)上创建索引。

因此,模式定义应类似于以下内容(请检查您是否不在使用 MySQL)

<?php

	// ...
	Schema::create('users', function (Blueprint $table) {
		$table->string('username', 32);
		$table->string('password', 50);
	});

	DB::statement('ALTER TABLE `usersb` ADD `id` BINARY(16); ALTER TABLE `usersb` ADD PRIMARY KEY (`id`);')
?>

关于此特定特质的两个附加说明。

说明 1. 为了获取您的 uuid 的字符串表示形式,只需调用 $model->id_string 即可。

说明 2. 您可以使用 User::find($uuid) 来使用二进制版本或字符串(bin2hex)版本。

使用优化的 uuid

要使用优化的 uuid,请将以下行放在您的模型中: private static $uuidOptimization = true;

在您的模型中

为了在您的模型中使用它,只需放置 use Uuid[32|Binary]ModelTrait;

<?php

namespace App;
use Alsofronie\Uuid\Uuid[32|Binary]ModelTrait;

class User extends Eloquent
{
	use Uuid[32|Binary]ModelTrait;
}

运行测试

要运行测试,只需运行 composer install./vendor/bin/phpunit