cakephp更新更多字段唯一 [英] cakephp update more field unique
问题描述
我有一个用cakephp开发的网站。
我有一个名为User的模型,如下所示:
I have a site developed in cakephp. I have a model called User like this:
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
检查数据库内部是否已经存在另一封相等的电子邮件。
Into my validate I have the rules email_unique
that check if inside the database is already present another email equal.
当我更新用户时,
$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');
}
它总是会失败,因为电子邮件不是唯一的但是相同的记录!
It always fail because email isn't unique but is the same record!
我想知道,如果保存是更新而不是创建,那么逃避验证的最佳方法是什么?
或类似的东西:检查页面是否是编辑转义验证或我不知道..也许有很多系统,我想知道什么对我的问题更正确。
I would like to know what is the best method to escape the validation if the save is an update not a create? Or something like: check if the page is edit escape validation or I don't know.. maybe there are many system, I would like to know what is the more correct for my problem.
谢谢
推荐答案
您可以将验证规则调整为仅在创建新记录时适用,而不是在更新现有记录时。您可以通过将验证规则中的 on
键设置为 create
来实现,因此如下所示:
You can adjust your validation rules to only apply when a new record is created, not when an existing record is updated. You can do this by setting the on
key in your validation rule to create
, so it will look like this:
'email_unique' => array(
'rule' => 'isUnique',
'message' => 'Mail already exist inside database',
'on' => 'create' // Only apply this rule upon creation of a new record
)
请参见文档,以获取更多详细信息。
See the documentation on this for further details.
如果您还想在更新时阻止重复的电子邮件,请创建一个 beforeSave 方法在您的用户模型中,查找电子邮件地址:
If you also want to block duplicate e-mails upon updating, create a beforeSave method in your User model, looking for the e-mail address:
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;
}
}
}
这篇关于cakephp更新更多字段唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!