
Bug编译狮
在Laravel Eloquent中使用UUID(Universally Unique Identifier)和ULID(Universally Unique Lexicographically Sortable Identifier)是一种常见的做法,以确保数据库中的数据是唯一的,并且易于排序。以下是实现这两种方法的步骤:
使用UUID
-
安装
uuid包: 首先,你需要安装uuid包来生成UUID。composer require uuid/uuid -
创建一个模型并使用UUID: 创建一个新的Eloquent模型,并在其中使用UUID作为主键。
use IlluminateDatabaseEloquentModel; use RamseyUuidUuid; class User extends Model { protected $primaryKey = 'uuid'; public $incrementing = false; public function __construct(array $attributes = []) { parent::__construct($attributes); $this->uuid = Uuid::uuid4(); } } -
插入数据: 当你尝试插入数据时,Laravel会自动为UUID字段赋值。
$user = new User(); $user->save(); dd($user->uuid); // 输出 UUID
使用ULID
-
安装
ulid包: 然后,你需要安装ulid包来生成ULID。composer require ulid/ulid -
创建一个模型并使用ULID: 创建一个新的Eloquent模型,并在其中使用ULID作为主键。
use IlluminateDatabaseEloquentModel; use UlidUlid; class User extends Model { protected $primaryKey = 'ulid'; public $incrementing = false; public function __construct(array $attributes = []) { parent::__construct($attributes); $this->ulid = Ulid::make(); } } -
插入数据: 当你尝试插入数据时,Laravel会自动为ULID字段赋值。
$user = new User(); $user->save(); dd($user->ulid); // 输出 ULID
示例代码
以下是一个完整的示例,展示了如何在Laravel Eloquent中使用UUID和ULID。
use IlluminateDatabaseEloquentModel;
use RamseyUuidUuid;
use UlidUlid;
class User extends Model
{
protected $primaryKey = 'uuid';
public $incrementing = false;
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->uuid = Uuid::uuid4();
}
public static function createWithUUID()
{
return self::create([
'name' => 'John Doe',
'email' => 'john.doe@example.com',
]);
}
public static function createWithULID()
{
return self::create([
'name' => 'Jane Smith',
'email' => 'jane.smith@example.com',
]);
}
}
// 插入数据
$userWithUUID = User::createWithUUID();
$userWithULID = User::createWithULID();
dd($userWithUUID->uuid); // 输出 UUID
dd($userWithULID->ulid); // 输出 ULID
通过这种方式,你可以轻松地在Laravel Eloquent中使用UUID和ULID来确保数据库中的数据是唯一的,并且易于排序。

黑板Bug讲师
介绍
在开发Web应用程序时,使用数据库记录的唯一标识符至关重要。传统上,数据库使用自动递增整数作为主键。然而,随着应用程序规模扩大和分布式系统的普及,需要更强大的解决方案来满足需求。进入UUID(全局唯一标识符)和ULID(全球唯一可排序标识符)。本教程将指导您如何在Laravel的Eloquent中使用UUID和ULIDs。
UUIDs, or Universally Unique Identifiers, are identifiers used to uniquely identify resources in a computer system. They are often used as part of the structure for network addresses and other unique identifier requirements. UUIDs are designed to be globally unique across different computing environments, making them suitable for use in various applications such as database records, software components, and distributed systems.
UUID是一种用于唯一标识计算机系统中的信息的128位数字。生成两个UUID相同的概率极其低。UUID有不同版本;对于本教程的目的,我们将专注于版本4(随机)。
ULIDs, also known as Unified Local Identifiers, are a set of identifiers used to uniquely identify devices and services within local networks. They provide a standardized way for devices to communicate with each other without relying on external infrastructure such as the internet. ULIDs are commonly used in IoT (Internet of Things) applications where there is a need for secure and reliable communication between devices within a specific network.
ULID是一种新的标识符,类似于UUID,但具有以下优点:例如,它可以进行字母排序,这意味着它们可以按创建时的顺序进行字母排序并保持升序排列。ULIDs在26个字符中编码,而UUID则有36个字符,因此对于存储来说更加紧凑。
设置 Laravel 并创建 Eloquent 模型。
在深入实施UUID和ULIDs之前,请确保您已正确设置并运行Laravel项目。创建一个用于演示的Eloquent模型。
php artisan make:model Product这会创建一个新的模型,如果需要的话,还会生成一个迁移文件。
在Laravel的Eloquent ORM中使用UUIDs(通用唯一识别码)是一种常见的做法,可以提高数据的一致性和可读性。以下是如何在Laravel中实现这一点的基本步骤: 首先,在config/app.php文件中注册一个新服务提供者。 ‘providers’ => [ // 其他服务提供者… AppProvidersAppServiceProvider::class, AppProvidersEventServiceProvider::class, AppProvidersRouteServiceProvider::class, AppProvidersDatabaseUuidServiceProvider::class, // 注册新的服务提供者 ], 然后创建一个新的服务提供者类来处理UUIDs。 namespace AppProviders; use IlluminateSupportFacadesSchema; use IlluminateSupportServiceProvider; use IlluminateSupportFacadesDB; use IlluminateSupportFacadesSchemaBlueprint; use IlluminateSupportFacadesSchemaBlueprint; class DatabaseUuidServiceProvider extends ServiceProvider { public function boot() { Schema::defaultStringLength(191); DB::statement(‘CREATE TABLE IF NOT EXISTS uuid_table (id BIGINT AUTO_INCREMENT PRIMARY KEY, value VARCHAR(36))’); } public function register() { // } } 在这个例子中,我们定义了一个名为uuid_table的新表,该表包含两个字段:id和value。id字段是主键,value字段用于存储生成的UUID。 在控制器或模型中使用UUID字段。 例如,在控制器中: use AppModelsUser; $user = User::find($id); $uuid = $user->id; // 获取用户ID对应的UUID 或者在模型中: use AppModelsUser; class User extends Model { protected $table = ‘uuid_table’; } 最后,确保数据库连接配置正确,并且有适当的权限来执行SQL语句。 通过以上步骤,你可以轻松地在Laravel中使用UUIDs进行数据管理。这不仅可以帮助你更好地管理和维护数据,还可以提高系统的可靠性和性能。
让我们先修改我们的新产品模型的迁移文件,使其使用UUID。
<?php
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
class CreateProductsTable extends Migration
{
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('products');
}
}
下一步,修改Eloquent模型以在创建时设置UUID:
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
use IlluminateSupportStr;
class Product extends Model
{
public $incrementing = false;
protected $keyType = 'string';
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
if (empty($model->{{id}})) {
$model->{{id}} = Str::uuid();
}
});
}
}
创建控制器中的新产品时,它会自动获得一个UUID:
$product = Product::create(['name' => 'Example Product']);
// $product->id would be a UUID like e.g., '123e4567-e89b-12d3-a456-426614174000'
在Laravel的Eloquent模型中使用ULID(Universally Unique Lexicographical ID)。
对于ULIDs,流程非常相似。修改迁移文件以期望字符串作为主键:
...
$table->string('id', 26)->primary();
...
在我们的产品模型中,我们将自动生成ULID:
use UlidUlid;
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
if (empty($model->{{id}})) {
$model->{{id}} = (string) Ulid::generate();
}
});
}
在控制器上创建一个新产品并观察ULID:
$product = Product::create(['name' => 'New Product']);
// $product->id would be a ULID like e.g., '01F8MMBCVGACEVB4BC23T4HE6W'
根据UUID和ULID查询。
使用UUID或ULID查找记录与通过其他字段查询的方式一样简单:
$product = Product::find('01F8MMBCVGACEVB4BC23T4HE6W');
// If exists, $product will contain the product with that ULID
额外的担忧
在使用UUID和ULID时,特别是在处理大型数据集的索引和性能方面可能会遇到问题。为了解决这些问题,可以考虑以下几点:
通过使用适当的数据库类型或为UUIDs启用二进制存储来优化索引。
如果需要根据创建时间排序,则使用UUID版本1。
高级示例
创建一个自动生成的 Laravel 遍历表迁移,以便通过数据库引擎函数直接生成 ULIDs 或 UUID 作为主键,需要一些定制化。我将为您提供两种示例。请注意,不同数据库(如 MySQL、PostgreSQL 等)的数据库级别 UUID 或 ULID 生成可能依赖于特定的数据库类型,并且确保跨数据库兼容性可能需要基于数据库类型的条件逻辑。
UUIDs(通用唯一识别码)的例子。
以下是为具有UUID主键的表创建迁移时,你可以如何操作。假设你的数据库引擎支持UUID。
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
class CreateYourTableNameTable extends Migration
{
public function up()
{
Schema::create('your_table_name', function (Blueprint $table) {
$table->uuid('id')->primary(); // Using UUID as primary key
$table->string('name');
// other fields...
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('your_table_name');
}
}
ULIDs(Uniform Resource Locators)是一种用于唯一标识资源的系统,通常在互联网上使用。它们可以被用作URL、电子邮件地址或文件路径等。例如,一个典型的ULID可能看起来像这样: http://example.com/resource/unique-id-1234567890abcdefg ULIDs具有以下特点: 唯一性:每个ULID都是唯一的。 不可变性:一旦生成,就不能更改。 易于存储和传输:由于它们通常是字符串格式,因此易于存储和传输。 ULIDs广泛应用于各种场景,如网站导航、电子商务、社交媒体以及数据管理等领域。
对于ULIDs,由于大多数数据库没有内置的ULID功能,因此在处理时需要在应用程序代码中进行生成(例如,在模型的相应方法中)。creating迁移设置如下:然而,这是ULID作为主键的基本迁移设置:
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
class CreateYourTableNameTable extends Migration
{
public function up()
{
Schema::create('your_table_name', function (Blueprint $table) {
$table->char('id', 26)->primary(); // ULID is 26 characters long
$table->string('name');
// other fields...
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('your_table_name');
}
}
在您的Eloquent模型中,您会处理生成ULID:
use IlluminateDatabaseEloquentModel;
class YourModel extends Model
{
public $incrementing = false;
protected $keyType = 'string';
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
if (empty($model->{$model->getKeyName()})) {
$model->{$model->getKeyName()} = (string) UlidUlid::generate(); // Assuming you are using a ULID package
}
});
}
}
笔记
性能考虑:使用UUID或ULIDs作为主键可能会对大型数据集产生影响。在这些标识符的索引和存储空间方面,需要进行考虑。
数据库特定功能:像PostgreSQL这样的数据库通常内置了UUID的支持,而其他如MySQL的数据库则会将UUID作为字符串处理。
跨数据库兼容性:如果需要确保跨数据库兼容性,建议在应用层生成UUID或ULID,而不是在数据库级别生成。
结论。
综上所述,将UUID和ULID整合到Laravel Eloquent中可以提升分布式系统中唯一标识符的处理能力,促进扩展性,并确保冲突几乎不存在。

长工码奴1523
在 Laravel 5.4 中,你可以使用 UUID 和 ULID 做为数据库的主键。这些是两个不同的方法来生成随机字符串,但它们有一些共同点。
首先,让我们了解这两个术语:
- UUID:Universally Unique Identifier 是一种随机字符串,通常用于标识系统中的唯一实体。它由一系列十六进制数字组成,并且可以作为数据库的主键。
- ULID:Unique Local Identifier 是另一种随机字符串,通常用于标识本地系统中的唯一实体。它也由一系列十六进制数字组成,并且与 UUID 类似,但是它的范围比 UUID 更小(通常是 128 位),并且更常用于本地环境。
要使用这两种类型的字符串,你需要在你的模型类中定义一个名为 uuid 或 ulid 的属性。然后,在关联关系时,你可以将这两个字段传递给关联对象。以下是如何做到这一点的一个例子:
use IlluminateDatabaseEloquentModel;
class MyModel extends Model
{
protected $table = 'my_table';
public function someRelatedField()
{
return $this->belongsTo(MyOtherModel::class);
}
// 添加 uuid 或 ulid 属性
public function setUuidAttribute($value)
{
$this->attributes['uuid'] = $value;
}
}
在这个例子中,我们创建了一个名为 MyModel 的模型类,其中包含一个 someRelatedField 关联器。这个关联器返回一个 MyOtherModel 对象。我们还添加了两个方法:一个用于设置 uuid 属性,另一个用于获取 uuid 字段。
现在,假设我们有一个 MyOtherModel 类,它有如下结构:
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class MyOtherModel extends Model
{
protected $table = 'my_other_table';
// 其他字段...
}
// 在 Laravel Eloquent 中,我们可以使用 setUuidAttribute 方法来设置 UUID 字段
public function setUuidAttribute($value)
{
$this->attributes['uuid'] = $value;
}
这样,当我们在 setUuidAttribute 方法中调用 $this->attributes['uuid'] = $value; 时,Laravel 将自动将其转换为 UUID 字符串。这使得我们在关联关系中能够轻松地引用 UUID。
注意,如果你希望使用 ULID,那么你应该在关联关系的回调函数中传入一个参数,例如:
public function setUlidAttribute($value)
{
$this->attributes['ulid'] = $value;
}
然后,在关联关系的回调函数中,你可以像这样调用 setUlidAttribute 方法:
$relatedModel->setUlidAttribute($value);
这样,你就可以在关联关系中引用 ULID 字符串了。

