········例1·································
//控制器
$model->scenario='update';//指定场景
$model -> save();
//模型
public function rules()
{
return [
['name','required','message'=>'用户名不能为空'],
['age','required','message'=>'年龄不能为空','on'=>'create'],
['pwd','required','message'=>'密码不能为空','on'=>'update']
];
}
//结果
验证name和pwd
········例2·································
//控制器
$model->scenario='update';
$model -> save();
//模型
public function scenarios()
{
return [
'update'=>['pwd'],
];
}
public function rules()
{
return [
['name','required','message'=>'用户名不能为空'],
['age','required','message'=>'年龄不能为空','on'=>'create'],
['pwd','required','message'=>'密码不能为空','on'=>'update'],
['level','required','message'=>'等级不能为空','on'=>'update'],
];
}
//结果
验证pwd
········例3·································
//控制器
$model -> save();
//模型
public function scenarios()
{
return [
'update'=>['pwd'],
];
}
public function rules()
{
return [
['name','required','message'=>'用户名不能为空'],
['age','required','message'=>'年龄不能为空','on'=>'create'],
];
}
//结果
报错,缺少场景
········例4·································
//控制器
$model -> save();
//模型
public function scenarios()
{
return [
'update'=>['pwd'],
'default'=>['name']
];
}
public function rules()
{
return [
['name','required','message'=>'用户名不能为空'],
['level','required','message'=>'等级不能为空'],
['age','required','message'=>'年龄不能为空','on'=>'create'],
];
}
//结果
验证name
········例5·································
//控制器
$model -> save();
//模型
public function rules()
{
return [
['name','required','message'=>'用户名不能为空'],
['age','required','message'=>'年龄不能为空','on'=>'create'],
];
}
//结果
验证name
总结:
1、rules没指定场景的话是公共规则
2、scenarios存在的话,只验证[]里的字段,优先级比rules高
3、scenarios存在的话,控制器一定要指定场景,否则添加'defaut'=>[字段]