在 Yii 2 下,[[yii\validators\UniqueValidator|unique(唯一性)]],组合字段的唯一性,在公共的模型逻辑层中自定义错误信息

1、/common/models 目录中的模型类文件仅允许Gii工具所生成,为公共的模型数据层,\common\models\ConfigColumn.php,模型的相关验证规则

    /**
     * {@inheritdoc}
     */    public function rules()
    {
        return [
            [['group_id', 'code', 'name'], 'required'],
            [['status', 'created_at', 'updated_at'], 'integer'],
            [['group_id', 'code', 'name'], 'string', 'max' => 32],
            [['group_id', 'code'], 'unique', 'targetAttribute' => ['group_id', 'code']],
            [['group_id', 'name'], 'unique', 'targetAttribute' => ['group_id', 'name']],
        ];
    }

2、/common/logics 目录中的模型类文件为业务逻辑相关,继承至 /common/models 数据层,为公共的模型逻辑层,\logics\ConfigColumn.php,模型的相关验证规则

    /**
     * @inheritdoc
     */    public function rules()
    {
        $rules = [
        ];
        $parentRules = parent::rules();

        return ArrayHelper::merge($rules, $parentRules);
    }

3、POST http://api.pcs-api.localhost/v1/config-columns?login_id=e56db1b43546a110431ac38409ed8e9e&login_tid=ccffd87b68171e8cb6c19f4bb8ccd775 ,422响应

{
    "code": 20004,
    "message": "Data validation failed: The combination \"015ce30b116ce86058fa6ab4fea4ac63\"-\"wxcq\" of Group ID and Code has already been taken."
}
{
    "code": 20004,
    "message": "数据验证失败:The combination \"015ce30b116ce86058fa6ab4fea4ac63\"-\"wxcq\" of 租户ID and 栏目代码 has already been taken."
}

4、分析源代码,\vendor\yiisoft\yii2\validators\UniqueValidator.php

        if (is_array($this->targetAttribute) && count($this->targetAttribute) > 1) {
            // fallback for deprecated `comboNotUnique` property - use it as message if is set
            if ($this->comboNotUnique === null) {
                $this->message = Yii::t('yii', 'The combination {values} of {attributes} has already been taken.');
            } else {
                $this->message = $this->comboNotUnique;
            }
        } else {
            $this->message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
        }

5、’The combination {values} of {attributes} has already been taken.’ 在框架自带的中文简体语言包中不存在,如图1

图1

6、’The combination {values} of {attributes} has already been taken.’ 在框架自带的英文语言包中存在,但是源语言未翻译,如图2

图2

7、/common/models 目录中的模型类文件仅允许Gii工具所生成,不允许再次编辑,自定义错误信息,只能够在 \logics\ConfigColumn.php 中实现,注:如果 \common\models\ConfigColumn.php 的 rules() 有变动,\logics\ConfigColumn.php 也需要相应的调整。

    /**
     * @inheritdoc
     */    public function rules()
    {
        $rules = [
            [['group_id', 'code'], 'unique', 'targetAttribute' => ['group_id', 'code'], 'message' => Yii::t('app', 'The combination {values} of {attributes} has already been taken.')],
            [['group_id', 'name'], 'unique', 'targetAttribute' => ['group_id', 'name'], 'message' => Yii::t('app', 'The combination {values} of {attributes} has already been taken.')],
        ];
        $parentRules = parent::rules();

        unset($parentRules[3], $parentRules[4]);

        return ArrayHelper::merge($rules, $parentRules);
    }

8、编辑 \common\messages\zh-CN\app.php

<?php
return [
    'The combination {values} of {attributes} has already been taken.' => '组合{attributes}的值"{values}"已经被占用了。',
];

9、编辑 \api\messages\zh-CN\app.php

<?php
return [
    'The combination {values} of {attributes} has already been taken.' => '组合{attributes}的值"{values}"已经被占用了。',
];

10、POST http://api.pcs-api.localhost/v1/config-columns?login_id=e56db1b43546a110431ac38409ed8e9e&login_tid=ccffd87b68171e8cb6c19f4bb8ccd775 ,422响应,如图3

图3

{
    "code": 20004,
    "message": "Data validation failed: The combination \"015ce30b116ce86058fa6ab4fea4ac63\"-\"wxcq\" of Group ID and Code has already been taken."
}
{
    "code": 20004,
    "message": "数据验证失败:组合租户ID and 栏目代码的值\"\"015ce30b116ce86058fa6ab4fea4ac63\"-\"wxcq\"\"已经被占用了。"
}

 

永夜