簡體   English   中英

yii2 唯一驗證器僅當字段不為空時

[英]yii2 unique validator only when field not empty

在 Yii2 中,我的數據庫中有兩個字段: emailshopId

  • EmailshopId一起應該是unique
  • Email也可以為empty ( NULL ) 而shopId始終是一個整數

這些是我在模型中的規則:

[['email'],'default','value' => NULL],
[['shopId'], 'integer'],
[['email','shopId'], 'unique', 'targetAttribute' => ['email', 'shopId'], 'message' => 'Already taken!'],

當我有兩個條目時,這不起作用,例如email="NULL"shopId="1"

我該如何解決這個問題?

當您的解決方案有效時,它在技術上並不正確。 驗證規則

[['email','shopId'], 'unique', 'targetAttribute' => ['email', 'shopId']]

如果email不為空(所需功能),將驗證email與給定shopId唯一性,但如果shopId不為空(不需要),它也會驗證shopId與給定email唯一性。 您正在使用對 DB 的兩個查詢來驗證兩個字段。

符合您需求的驗證規則是

[['email'], 'unique', 'targetAttribute' => ['email', 'shopId']]

說“如果email不為空,請檢查emailshopId組合是否唯一並將結果綁定到email屬性”。

skipOnEmpty屬性設置為false http://www.yiiframework.com/doc-2.0/yii-validators-validator.html# $skipOnEmpty-detail

我在規則中使用了 when 條件

[
    ['email', 'shopId'],
    'unique',
    'targetAttribute' => ['email', 'shopId'],
    'message' => 'Diese E-Mail Adresse ist bereits registriert!',
    'when' => function ($model) {
        return !empty($model->email);
    }
],

我創建了一個解決方案來強制跨一組字段的唯一性,包括可空字段,它利用yii\\validators\\UniqueValidator::$filter回調在通用 PHP Trait 中可以簡單地放入任何 Yii2 模型中。 完整代碼示例如下:

通用特征[common/models/traits/UniqueValidatorFilterTrait.php]

<?php

namespace common\models\traits;

use yii\db\ActiveQuery;

/**
 * Trait UniqueValidatorFilterTrait provides custom anonymous function callback methods.
 *
 * @package common\models\traits
 * @author Alec Pritchard <ajmedway@gmail.com>
 */
trait UniqueValidatorFilterTrait
{
    /**
     * Custom anonymous function for [[yii\validators\UniqueValidator::$filter]], used to modify the passed-in
     * [[\yii\db\ActiveRecord]] query to be applied to the DB query used to check the uniqueness of the input value.
     *
     * @param ActiveQuery $query
     * @param array $nullableUniqueFields the field names to ensure are considered and validated for the uniqueness
     * of a set of model attributes, even if some have empty/null values.
     * @see \yii\validators\UniqueValidator::$filter
     */
    public function filterFunctionUniqueWithNull(ActiveQuery $query, array $nullableUniqueFields = [])
    {
        // check if at least one of the $nullableUniqueFields currently has an empty value loaded
        $hasEmptyUniqueField = false;
        foreach ($nullableUniqueFields as $field) {
            if (empty($this->{$field})) {
                $hasEmptyUniqueField = true;
                break;
            }
        }
        // proceed to modify AR query
        if ($hasEmptyUniqueField) {
            // change query item for the $nullableUniqueFields, which only checks against empty string by design
            // @link https://github.com/yiisoft/yii2/issues/4333#issuecomment-57739619
            // ensure the composite unique constraint is applied to include NULL values for all $nullableUniqueFields
            foreach ($query->where as $whereItemKey => $whereItem) {
                if (!is_array($whereItem)) continue;
                foreach ($whereItem as $columnName => $value) {
                    // check if this column is one of the unique fields and if it currently has an empty string
                    if (str_replace($nullableUniqueFields, '', $columnName) != $columnName
                        && $value === '') {
                        // change from '' to NULL
                        $query->where[$whereItemKey][$columnName] = null;
                    }
                }
            }
        }
    }
}

示例模型使用

<?php

namespace common\models;

use Yii;
use common\models\traits\UniqueValidatorFilterTrait;

/**
 * This is the model class for table "my_table".
 *
 * @property int $id
 * @property null|string $email
 * @property int $shop_id
 */
class MyTable extends \yii\db\ActiveRecord
{
    use UniqueValidatorFilterTrait;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'my_table';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [
                ['email', 'shop_id'],
                'unique',
                'targetAttribute' => ['email', 'shop_id'],
                // ensure the composite unique constraint is applied to include NULL values for specified nullable fields
                'filter' => function (MyTableQuery $query) {
                    /* @see \common\models\traits\UniqueValidatorFilterTrait::filterFunctionUniqueWithNull() */
                    $this->filterFunctionUniqueWithNull($query, ['email', 'shop_id']);
                },
                // ensure that we don't skip on empty values, namely the `email` and/or `shop_id`
                'skipOnEmpty' => false,
            ],
        ];
    }

關於 Yii2 核心唯一驗證器的這個缺點的完整討論,以及核心開發團隊給出的原因在這里: https : //github.com/yiisoft/yii2/issues/4333

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM