2013-11-25 81 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