Answer the question
In order to leave comments, you need to log in
Yii2. How to roll back the added data?
I have if constructs
in which an entry is added to a specific database table, depending on the conditions.
Tell me how to roll back the added data if an error occurred in the nested conditions when adding?
Answer the question
In order to leave comments, you need to log in
Well, I would start by simplifying the code itself (if there are a lot of if constructs).
But one solution is to use try/catch, and before that, make a transaction through Yii::$app->db->beginTransaction();
If an error occurs - throw new MyException(); and in the catch block - Yii::$app->db->rollBack();
If everything is in order - at the end of try add Yii::$app->db->commit();
Look at the documentation, there is a similar code example www.yiiframework.com/doc-2.0/yii-db-connection.html
Read about transactions in Yii. Just wrap it in a transaction and rollback if necessary.
www.yiiframework.com/doc-2.0/guide-db-dao.html#per...
thanks to all. did like this:
$transaction = Yii::$app->db->beginTransaction();
try {
...
$transaction->commit();
} catch (\Exception $e) {
$transaction->rollBack();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question