Yii 2.0 rollBack()

Yii 2.0 rollBack()

In this post I want to talk about rollBack() and how to use this function. What is rollBack()? Imagine you have a table called 'Product' and a table called 'Files'. You store files related to a product in 'Files'.


In this post I want to talk about rollBack() and how to use this function.

What is rollBack()?

Imagine you have a table called 'Product' and a table called 'Files'. You store files related to a product in 'Files'. So you have to store 'Product's primary key in 'Files'. As a result, first you have to save 'Product' then its 'Files'. Imagine we want to delete a product. We have to delete the files as well. So what happens if we have deleted the product, but the files aren't deleted? We use rollBack to make sure that if the action of deleting its files has failed and we have already deleted our product, we undo deleting the product and the record still remains in our database. In other words, we use rollBack() to make sure that the database properly changes states upon a successfully committed transaction.

How can we use rollBack()?

You can use rollBack() in the following way:

$connection  = new \yii\db\Connection([
    'dsn' => Yii::$app->db->dsn,
    'username' => Yii::$app->db->username,
    'password' => Yii::$app->db->password,
]);
$transaction = $connection->beginTransaction();
try {
    //Deleting the product
    $connection->createCommand($sql1)->execute();
    //Deleting the files
    $connection->createCommand($sql1)->execute();
    //.... other SQL executions
    $transaction->commit();
} catch (Exception $e) {
    $transaction->rollBack();
}

At first, you start your transaction to tell Yii the following commands should be done one after each other. In try{} you have to write your sql commands using createCommand(). After writing all your commands you should tell Yii that you want to commit your transaction. This is done using commit(). After try{}, you need to have a block as catch(){} to catch your errors. This tells Yii that do the following, if there any errors occurs. Then, in that block use rollBack() to undo whatever that has happened!