【问题标题】:cakephp update more field uniquecakephp 更新更多字段唯一
【发布时间】:2013-11-26 05:35:19
【问题描述】:

我有一个用 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');
}

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

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

谢谢

【问题讨论】:

    标签: php cakephp


    【解决方案1】:

    您可以调整验证规则,使其仅在创建新记录时应用,而不是在更新现有记录时应用。您可以通过将验证规则中的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;
            }
        }
    }
    

    【讨论】:

    • 嗯...那么,如果您使用已在另一条记录中的电子邮件更新现有记录怎么办?
    • 好点@AbraCadaver,因为这是一个很小的问题,但不是那么容易做到
    • 在这种情况下,请使用beforeSave 进行仔细检查。查看更新的答案。
    猜你喜欢
    • 1970-01-01
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 2018-08-09
    相关资源
    最近更新 更多