yii2 unique validation not working

2019-07-13 18:22发布

问题:

Yii2 Unique Validation not working for combination of employee id and company id Below are my model code.

            public function rules()
                {
                    return [
                        [['company_id', 'role_id'], 'required'],
                        [['company_id', 'role_id', 'status'], 'integer'],
                        [['employee_id'], 'string', 'max' => 15],
                        [['report_to'], 'string', 'max' => 16],
                        [['id',],'safe'],
                        ['employee_id', 'unique', 'targetAttribute' => ['company_id', 'employee_id'], 'message' => 'The combination of Company ID and Employee ID has already been taken.']
                        // ['employee_id', 'unique', 'targetAttribute' => ['company_id'], 'message' => 'The combination of Company ID and Employee ID has already been taken.']
                    ];
                }'

And this my controller code

                $model = new Employee();
                //$profile = new Profile();
                // $profile->scenario = 'emp_bulk_uplscenariooad';
                if($model->load(Yii::$app->request->post())) {
                    $model->company_id = $userModel->company_id;

                    $model->employee_id = Yii::$app->request->post()['Employee']['employee_id'];

                    $model->role_id = Yii::$app->request->post()['Employee']['role_id'];
                    $model->report_to = Yii::$app->request->post()['Employee']['report_to'];
                        // print_r(!$model->validate());die();
                        if($model->save(false)){
        }

*************************************************************************

    please help me with this.thanks in advance

回答1:

You use

  if($model->save(false)){ 

this mean no validation are performed

try using

   if($model->save()){ 

and in actioCreate you should recall render create if model->save() fail

public function actionCreate()
{
    $model =  new Employee();

    if($model->load(Yii::$app->request->post())) {
        $model->company_id = $userModel->company_id;

        $model->employee_id = Yii::$app->request->post()['Employee']['employee_id'];

                $model->role_id = Yii::$app->request->post()['Employee']['role_id'];
                $model->report_to = Yii::$app->request->post()['Employee']['report_to'];
        // print_r(!$model->validate());die();
         if($model->save()){
            return $this->redirect(['view', 'id' => $model->id]);
         }
        else {
           return $this->render('create', [
            'model' => $model,
           ]);
       }
}


回答2:

Try performing composer update, there was a Yii2 bug fixed that was tied to unique validator when using relational data in addition to other scenarios:

See the following: https://github.com/yiisoft/yii2/issues/14211