CAKEPHP: 唯一性数据验证任务不能正常工作

遇到如下情况: 想要验证某个字段的合法性,

包含两条规则,一条是CakePHP自带的isUnique方法用来检查该字段在数据库中的唯一性

另外一条是限制该字段的输入字符集

public $validate = array(
'slug' => array(
'isUnique' => array(
'rule' => array('isUnique'),
'message' => 'This slug has already been taken.',
),
'charsAllowed' => array(
'rule' => '/^[a-z0-9_-\s]{1,}$/i',
'message' => 'Slug can only be alpha,number,space,_,-'
),
),
);

看起来没问题,实际第一个isUnique验证规则不能正常工作。

原因是CAKEPHP默认Model自带的isUnique方法中为字段查询语句自动添加了OR条件,

而OR条件在当前CAKEPHP版本不能像CAKEPHP book中所述的那样工作。

解决方法是定制自己的唯一性检查, 验证规则修改如下:

public $validate = array(
'slug' => array(
'slug' => array(
//overwrite the cake's default method isUnique,
//as the OR condition didn't work as expected
'rule' => array('unique',false),
'message' => 'This slug has already been taken.',
),
'charsAllowed' => array(
'rule' => '/^[a-z0-9_-\s]{1,}$/i',
'message' => 'Slug can only be alpha,number,space,_,-'
),
),
);

function unique($con, $or) {

......

return ($this->find('count', array('conditions' => $con, 'recursive' => -1)) == 0);

}

你可能感兴趣的:(工作,cakephp)