我有两张桌子:
地区表
create table if not exists Region (
id int(2) unsigned not null auto_increment,
name varchar(40) unique not null,
code varchar(9) not null,
primary key(id)
);
省表:
create table if not exists Province (
id int(2) unsigned not null auto_increment,
region_id int(2) unsigned not null,
name varchar(40) unique not null,
code varchar(9) not null,
primary key(id),
key region_id(region_id),
constraint province_region_id foreign key(region_id) references region(id)
);
示例数据:
region_code:010000000
province_code:010100000
它们是相关的,因为它们具有相同的前两个字符
我创建了一个部分自定义验证,但我无法完成它甚至不知道使用带有arrayhelper组合的substr()是否正常
public function modelCodeValidator()
{
$regCode=>substr([Arrayhelper::map(Region::find()->all()->,'id','code')],2);// specifying first two character of region.code
$provCode=>substr('code',2);//specifying first two character of province.code
return [$regCode=$provCode];
}
在这个自定义验证上,rule()将是:
['code','compare','modelCodeValidator' don't know next]
region_code的前两个字符应匹配/等于province_code的前两个字符。通过这样做,用户将通知他们只能输入属于特定区域的省代码。请帮助
答案 0 :(得分:0)
尝试这样的事情......
public function rules()
{
return [
['code', 'modelCodeValidator'],
];
}
public function modelCodeValidator($attribute, $params)
{
// Write your coding stuff here
if (YourModelName::findOne(['your_model_field'=> $attribute]) {
$this->addError($attribute, \Yii::t('view', 'The fields don't match.'));
}
}
看看这里: - > http://www.yiiframework.com/doc-2.0/guide-input-validation.html#client-side-validation