monurakkaya/laravel-unique-code-generator

为您的模型提供唯一代码

v1.0.2 2022-06-24 02:42 UTC

This package is auto-updated.

Last update: 2024-09-24 07:55:48 UTC


README

为您的 Eloquent 模型提供唯一代码

安装

composer require monurakkaya/laravel-unique-code-generator

用法

模式

创建列

// This will generate an unique string column named `code` 255 length which equivalent to $table->string('code', 255)->unique();
Schema::create('table', function (Blueprint $table) {
    ...
    $table->uniqueCode();
});

删除列

Schema::table('table', function (Blueprint $table) {
    $table->dropUniqueCode();
});

要使用自己的列,只需传递参数以覆盖默认值

// on create
$table->uniqueCode('my_code', 'bigInteger', 32); // columnName, columnType, columnLength

// on drop
$table->dropUniqueCode('my_code');

使用模式助手是可选的。您可以使用自己的定义继续。

模型

您的模型应该使用 Monurakkaya\Lucg\HasUniqueCode 特性以启用唯一代码功能

use Monurakkaya\Lucg\HasUniqueCode;

class Foo extends Model {
    use HasUniqueCode;
}

这样就完成了。

$foo = Foo::create(['title' => 'Foo']);
#attributes: array:10 [▼
    "id" => 1
    "code" => "OF0EIL8B"
    "title" => "Foo"
    "created_at" => "2022-01-24 13:11:03"
    "updated_at" => "2022-01-24 13:11:03"
  ]

设置

要更改列名,只需在您的模型上覆盖 uniqueCodeColumnName 方法


class Foo extends Model {
    use HasUniqueCode;
    
    protected static function uniqueCodeColumnName()
    {
        return 'my_code';
    }
}

** 确保您的代码列名与列名相等。默认为 code

要更改代码类型,只需在您的模型上覆盖 uniqueCodeType 方法


class Foo extends Model {
    use HasUniqueCode;
    
    protected static function uniqueCodeType()
    {
        return 'numeric';
    }
}

可用类型为 'random_uppercase', 'random_lowercase', 'uuid', 'numeric'。默认为 random_uppercase

** 如果您打算使用 uuid,我建议您将列定义设置为 uuid

要更改代码长度,只需在您的模型上覆盖 uniqueCodeLength 方法


class Foo extends Model {
    use HasUniqueCode;
    
    protected static function uniqueCodeLength()
    {
        return 32;
    }
}

** 确保您的代码长度小于等于列长度。默认为 8

测试

要运行测试,请在项目根目录中从命令行执行以下操作

./vendor/bin/phpunit