S
S
Stanislav2016-07-16 21:41:02
Yii
Stanislav, 2016-07-16 21:41:02

Yii2: how does unique work in server validation?

I exaggerate for convenience.
Let's say I have a Users.php model , there is nothing interesting in it, just a model, inherits AR, corresponds to a simple table with users: id , userName , userPassword .
There is a second model - Signup.php - respectively used to register a new user. It has a method:

public function rules()
  {
    return [
        [['userName','userPassword'],'required'],
        ['userName','unique','targetClass'=>'app\models\Users'],
    ];
  }

And a method for directly entering verified data into the database through the Users model:
public function signup()
  {
    $user = new Users;
    $user->userName = $this->userName;
    $user->userPassword = $this->userPassword;
    return $user->save();
  }

In the controller this kind of code:
public function actionSignup()
    {
        $model = new Signup();
        if( \Yii::$app->request->post('Signup') )
        {
            $model->attributes = \Yii::$app->request->post('Signup');

            if($model->validate() && $model->signup())
            {
                return $this->goHome();
            }
        }
        return $this->render('signup',['model'=>$model]);
    }

In representation the elementary form.
Question: How is uniqueness checked? In the official documentation, they stupidly put before the fact - it checks and that's it.

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
H
holfza, 2016-07-16
@Stasgar

An additional query is made to the database, it's obvious. You can look in the debug panel.
PS In your code, validation is performed 2 times, it will probably be more correct like this:
return $user->save(false);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question