我有两个表table1
,每个表都有一个与不同的其他列一起table2
命名的列。我想要的是一个验证器,它在两列的字段中email
寻找唯一性。email
我找到了一个检查SAME表的多个列的扩展。如何扩展它以使其适用于多个列?
2 回答
您可以使用 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 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',
)),
}
}
在Yii2
短的:
['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']
]