YII2规则中的自定义验证无效
我已经在我的模型中这样做了:YII2规则中的自定义验证无效,yii,yii2,Yii,Yii2,我已经在我的模型中这样做了: public function rules() { return [ [['category_name'], 'required','message' => 'Please enter {attribute}.'], [['category_name'], 'string', 'max' => 45], [['category_name'], 'safe', 'on' =>
public function rules() {
return [
[['category_name'], 'required','message' => 'Please enter {attribute}.'],
[['category_name'], 'string', 'max' => 45],
[['category_name'], 'safe', 'on' => 'search'],
['category_name', 'checkName'],
];
}
public function checkName($attribute, $params) {
$model = Categories::find()->where('category_name = "' . $this->$attribute . '" AND status != ' . Categories::STATUS_DELETED)->all(); //STATUS_DELETED = 2 constant.
if (count($model) > 0) {
$this->addError($attribute, 'Category name is already exists.');
}
}
问题在于,输入重复值时,checkName函数未触发。可能的原因是什么?好的,有一个小问题,实际上表名是categories,模型只是categories,因此将模型名更改为categories解决了问题。是否通过在categories::STATUS_DELETED->all;中正确关闭来检查?是的,它已正确关闭。您只需使用唯一验证程序即可