L
L
lolka022020-02-25 08:37:03
Yii
lolka02, 2020-02-25 08:37:03

Why doesn't unique work in Yii2 model?

In general there is a console command Hello there is an action Test. when running several such processes at the same time, duplicates are obtained and the unique validation in the model does not work

public function actionTest()
    {
        $email = '[email protected]';
        $doubleModels = Test::findOne(['email' => $email]);
        if (!$doubleModels) {
            $model = new Test();
            $model->email = $email;
            $model->save();
        }
    }


And in the Test.php model there is a validation

/**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            ['email', 'unique'],
            [['email'], 'string', 'max' => 255],
        ];
    }


to check, I made several identical task crons and simultaneously run
23 */1 * * * cd /var/www/domain/data/www; /usr/bin/php yii hello/test
23 */1 * * * cd /var/www/domain/data/www; /usr/bin/php yii hello/test
23 */1 * * * cd /var/www/domain/data/www; /usr/bin/php yii hello/test
23 */1 * * * cd /var/www/domain/data/www; /usr/bin/php yii hello/test

It turns out 4 records, although the model has a unique email field.

How to fix such jambs? so that this does not happen in working scripts

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
Maxim, 2020-02-25
@lolka02

Try like this

public function actionTest()
    {
        $email = '[email protected]';
        $emailExists = Test::find()->where(['email' => $email])->exists();
        if (!$emailExists) {
            $model = new Test();
            $model->email = $email;
            $model->save(false);
        }
    }

A
Arman, 2020-02-25
@Arik

unique makes the request itself and checks for availability, several processes manage to check and write at the same time, so on the database side we put a unique key in the email field. mail

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question