cakephp更新更多字段唯一

时间:2013-11-25 21:12:02

标签: php cakephp

我有一个在cakephp中开发的网站。 我有一个名为User的模型:

class User extends AppModel {
    public $name = 'User';

    public $validate = array(
        'username' => array(
            'not_empty' => array(
                'rule'=> 'notEmpty',
                'message'=> 'Username not empty'    
            )
        ),
        'email' => array(
            'email_invalid' => array(
                'rule' => 'email',
                'message' => 'Invalid mail'
            ),
            'email_unique' => array(
                'rule' => 'isUnique',
                'message' => 'Mail already exist inside database'
            )
        )
    );


    public function beforeSave(){
           if (isset($this->data['User']['password'])){
            $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
        }
    }   
}

在我的验证中,我有规则email_unique,用于检查数据库中是否已存在另一封电子邮件等。

当我更新用户时,我在我的控制器中进行此操作:

$this->User->id = $this->request->data['User']['id'];
if ($this->User->save($this->request->data)) {
    $this->redirect (array ('action'=>'index'));
}
else{
    $this->Session->write('flash_element','error');
    $this->Session->setFlash ('Error');
}

它始终失败,因为电子邮件不是唯一的,但是记录相同!

如果保存是更新而不是创建,我想知道什么是逃避验证的最佳方法? 或类似:检查页面是否编辑转义验证或我不知道..也许有很多系统,我想知道什么是更正确的问题。

由于

1 个答案:

答案 0 :(得分:2)

您可以将验证规则调整为仅在创建新记录时应用,而不是在更新现有记录时应用。您可以通过将验证规则中的on键设置为create来执行此操作,因此它将如下所示:

'email_unique' => array(
    'rule' => 'isUnique',
    'message' => 'Mail already exist inside database',
    'on' => 'create' // Only apply this rule upon creation of a new record
)

有关详细信息,请参阅the documentation

如果您还想在更新时阻止重复的电子邮件,请在用户模型中创建beforeSave方法,查找电子邮件地址:

public function beforeSave($options = array()) {
    // If the email key is set in the data to be saved...
    if (isset($this->data[$this->alias]['email'])) {
        // Make sure the email is not already in use by another user
        if ($this->find('count', array(
            'conditions' => array(
                $this->alias . '.id !=' => $this->data[$this->alias]['id'],
                $this->alias . '.email' => $this->data[$this->alias]['email']
            )
        )) > 0) {
          // The email is found for a user with another id, abort!
          return false;
        }
    }
}