2013-11-25 84 views
0

我有一个在cakephp开发的网站。 我有一个名为用户喜欢这种模式:cakephp更新更多字段唯一

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'); 
} 

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

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

感谢

回答

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; 
     } 
    } 
} 
+1

嗯......所以,如果你更新了什么现有的记录与已经在另一个记录中的电子邮件? – AbraCadaver

+0

伟大的一点@AbraCadaver,因为是一个很小的问题,但不是那么容易做 –

+0

在这种情况下,使用'beforeSave'来做双重检查。查看更新的答案。 – Oldskool