Yii2模型规则更新相同记录的检查规则

时间:2015-12-24 05:08:13

标签: yii2 yii2-advanced-app yii2-model yii2-validation

即。如果我更新address_line1,那么它为分配的手机号码提供错误。 虽然更新它不应该与它自己匹配。 即使我更改手机号码,也应该与其他用户核对。

public function rules()
    {
        return [
                    [['mobile_number','address_line1','address_line2','city','state','country','pincode' ],'required'],
                    ['mobile_number','mobile_number_allocation_validate'],

        ];
    }

public function mobile_number_allocation_validate($attribute){
        // add custom validation
        $result = User::find()
        ->where('`mobile_number` = "'.$this->$attribute.'" AND 
                `status` = "A" ')->all();
        if(!empty($result)){
            $this->addError($attribute,'Mobile number is allocated to other vehicle');
        }

    }

先谢谢

2 个答案:

答案 0 :(得分:0)

将您的条件更改为: - 覆盖beforeSave()

User ActiveRecord
/**
 * BeforeSave() check if User ActiveRecord is created with same calculator param
 * if created then return false with model error
 *
 */
public function beforeSave($insert){
    $model = self::find()->where('`mobile_number` = "'.$this->$attribute.'" AND 
            `status` = "A" ')->all();

    if($model !== null && $model->id !== $this->id){
        $this->addError('mobile_number' , 'Mobile number is allocated to other vehicle');
        return false;
    }

    return parent::beforeSave($insert);
}

答案 1 :(得分:0)

您应该可以使用unique验证码,只需添加filter这样的条件

public function rules()
    {
        return [
            [['mobile_number','address_line1','address_line2','city','state','country','pincode' ],'required'],
            ['mobile_number','unique', 'filter' => ['status' => 'A']],
        ];
    }