2017-03-06 39 views
1

我正在yii2项目中工作。我有用户模型,该电子邮件ID应该是唯一的。在添加功能它正在工作。但是,当我更新记录它不检查独特的验证。如何在yii2中更新时检查唯一验证

以下是我的用户模型代码:

public function rules() { 
     return [ 
      [['first_name', 'last_name', 'address', 'mobile', 'email', 'password_hash', 'role_id'], 'required'], 
      [['address'], 'string'], 
      [['role_id'], 'integer'], 
      [['email'], 'email'], 
      [['email'], 'unique', 'targetAttribute' => ['email']], 
      [['created_at', 'updated_at'], 'safe'], 
      [['first_name', 'last_name', 'email', 'password_hash'], 'string', 'max' => 255], 
      [['mobile'], 'required','on'=>'create,update'], 
      //[['mobile'], 'string','max'=>10], 
      [['mobile'], 'number','numberPattern' => '/^[0-9]{10}$/','message'=>"Mobile must be integer and should not greater then 10 digit"], 
      [['password_hash'],'string','min'=>6], 
      //[['mobile'], 'number'], 
      [['status'], 'string', 'max' => 1,'on'=>'create,update'], 
      [['role_id'], 'exist', 'skipOnError' => true, 'targetClass' => Roles::className(), 'targetAttribute' => ['role_id' => 'id']], 
     ]; 
    } 

即使我尝试:[[ '电子邮件'], '独一无二', 'targetAttribute'=> [ '电子邮件'], '上' =>数组('创建','更新')],

但没有发生它不检查更新函数中的唯一规则。

+0

您不必添加'targetAttribute'如果它是与选中的一样。你为什么认为它不起作用? – Bizley

+0

是的,我删除了它仍然不工作更新页面 – David

+0

再次 - 为什么你认为它不工作?解释你期望的是什么,取而代之的是什么。 – Bizley

回答

0

如果检查栏是相同的请尝试使用

[['email'], 'unique'], 
0

TargetClass检查现有的电子邮件中DB与帮助用户模型

['email', 'filter', 'filter' => 'trim'], 
    ['email', 'required'], 
    ['email', 'email'], 
    ['email', 'unique', 'targetClass' => '\app\models\User', 'message' => 'This email address has already been taken.'], 
+0

感谢兄弟,但更新记录时这不起作用。\ – David