C
C
Carlos Rodriguez2015-01-17 12:44:49
Yii
Carlos Rodriguez, 2015-01-17 12:44:49

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

4 answer(s)
A
Andrey Pavlenko, 2015-01-17
@asf

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

R
Rikcon, 2015-01-17
@Rikcon

take last insert id and delete on this id from the table.

D
Dmitry Baibukhtin, 2015-01-17
@PiloTeZ

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...

C
Carlos Rodriguez, 2015-01-17
@asf

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 question

Ask a Question

731 491 924 answers to any question