P
P
Padre2017-07-12 21:38:25
Yii
Padre, 2017-07-12 21:38:25

How in Yii2 not to crash with an error when retrying in the database?

When writing data to the database

$phone = new Users();
$phone ->name= '89404445566';
$phone ->save();
if($phone->save()) {
   return 'Ок';
} else {
   return 'Ошибка';
}

There is a crash with the Duplicate entry for key error, but it's understandable why, the question is how to process it so as not to cause the application to crash?
1) The first option INSERT IGNORE can be used with the ActiveRecord method, if so, how to specify the addition of IGNORE to the query? Or here it is necessary to switch to Data Access Objects in order to write the request manually
2) The second option, as I understand it, you can catch an exception, but the exception is when the application can no longer work, and then you just want to continue and show a normal error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2017-07-12
@yii16

Good evening.
Remove the first save to the $phone ->save();
PS database
For this, in yii2, there is a validation. In this case , this built-in validator
will suit you , which will check the data transmitted by the user for uniqueness. If you try to transfer the same data, it will issue a warning. So, for example, you can check the e-mail address for uniqueness

// в модели, в правилах валидации пишите
['email', 'unique', 'targetClass' => self::className(),
                                'message' => 'Извините, такой e-mail уже существует в базе данных',

So you can check both logins and phones and whatever you want ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question