jamband/yii2-ensure-unique-behavior

此软件包已被弃用且不再维护。未建议替代软件包。

此扩展为 Yii 2 框架自动插入唯一标识符

v0.6.0 2021-11-26 12:19 UTC

This package is auto-updated.

Last update: 2022-10-26 18:49:27 UTC


README

Build Status Latest Stable Version Total Downloads

为 Yii 2 框架自动插入唯一标识符。

要求

  • PHP 7.4 或更高版本
  • Yii 2.x

安装

composer require jamband/yii2-ensure-unique-behavior

示例

创建一个帖子表

CREATE TABLE `post` (
    `id` CHAR(11) COLLATE utf8_bin NOT NULL,
    `title` VARCHAR(255) NOT NULL,
    `content` TEXT NOT NULL,
    `created_at` INT(11) NOT NULL,
    `updated_at` INT(11) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARACTER SET=utf8 COLLATE=utf8_unicode_ci;

在模型中设置 EnsureUniqueBehavior

namespace app\models;

use jamband\behaviors\EnsureUniqueBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

class Post extends ActiveRecord
{
    public function behaviors()
    {
        return [
            TimestampBehavior::class,
            [
                'class' => EnsureUniqueBehavior::class,
                'attribute' => 'id', // default
                'length' => 11, // default
            ],
        ];
    }
}

并保存新模型

$model = new \app\models\Post();
$model->title = 'title';
$model->content = 'content';
$model->save();

// This value is eusure uniqueness
var_dump($model->id); // string(11) "-ZRLSS-4vl_"

许可

此扩展基于 MIT 许可证。