Yii对不同表的两列进行唯一验证,即复合唯一验证

bweufnob  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(151)

我有两个表table1table2,每个表都有一个名为email的列沿着其他不同的列。我需要的是一个验证器,它在两个列的email字段中查找唯一性。我发现了一个extension,它检查SAME表的多个列。我如何扩展它,使它适用于多个列?

7uhlpewt

7uhlpewt1#

您可以使用className属性为其他类指定..
文件:the ActiveRecord class name that should be used to look for the attribute value being validated. Defaults to null, meaning using the class of the object currently being validated. You may use path alias to reference a class name here.
让我们在两个模型中使用一个名为common_attr的属性:

class Model1 extends CActiveRecord{
    public function rules(){
        array('common_attr', 'unique', 'className'=> 'Model1'),
        array('common_attr', 'unique', 'className'=> 'Model2'),
    }
}

class Model2 extends CActiveRecord{
    public function rules(){
        array('common_attr', 'unique', 'className'=> 'Model1'),
        array('common_attr', 'unique', 'className'=> 'Model2'),
    }
}

**若要检查多个表的combined key验证,您可以使用CUniqueValidator的criteria属性..**无需任何扩展

文件:criteria property public array $criteria; additional query criteria. This will be combined with the condition that checks if the attribute value exists in the corresponding table column. This array will be used to instantiate a CDbCriteria object.

class Model1 extends CActiveRecord{

    public function rules(){
        array('common_attr', 'unique', 'caseSensitive'=>false,
                   'criteria'=>array(
            'join'=>'LEFT JOIN model2 ON model2.common_attr=model1.common_attr',
                            'condition'=>'model2.common_attr=model1.common_attr',
        )),
    }
}
yeotifhr

yeotifhr2#

一2
简短:

['common_attr', 'unique'],
['common_attr', 'unique', 'targetClass' => AnotherClass::class],

详细信息:

class One extends \yii\db\ActiveRecord
{
    public function rules()
    {
        return [
            ['common_attr', 'unique'],
            ['common_attr', 'unique', 'targetClass' => Two::class],
        ];
    }
}

class Two extends \yii\db\ActiveRecord
{
    public function rules()
    {
        return [
            ['common_attr', 'unique'],
            ['common_attr', 'unique', 'targetClass' => One::class],
        ];
    }
}

此外,还可以将多个唯一键与targetAttribute一起使用:

[
    'common_attr', 
    'unique', 
    'targetClass' => One::class, 
    'targetAttribute' => ['common_attr', 'one_more_attr']
]

相关问题