Skip to content

Yii2 Transaction

Last updated on February 10, 2018

In this tutorial, I would like to show you how we can use transactions in YII2. A transaction is used to run a group of operations in the single process means a transaction is a unit of work.

Why should I use transaction?

In database we may need to perform add, update or delete operations on multiple tables while doing these operations on multiple tables if anything went wrong at one table few tables may be updated and few tables may not be updated. So there will be data inconsistency.Therefore, we want either a unit of work will be carried out completely or none. Hence the transaction is required to make it happen.

Here is the typical yii2 transaction template –

$transaction = $connection->beginTransaction();
try {
    $connection->createCommand($sql1)->execute();
    $connection->createCommand($sql2)->execute();
    //.... other SQL executions
    $transaction->commit();
} catch (\Exception $e) {
    $transaction->rollBack();
    throw $e;
}

Yii2 Transaction Example

In below example, first We will create new user and then created user will assigned to the role. If two query will execute successfully, the commit function will work. But when first or second query will make errors, Nothing will not happen inside transaction and it will roll baked to original state.

$transaction = $connection->beginTransaction();
try {
$user = $connection->createCommand()->insert('users', [
'name' => 'arjunphp',
'email' => '[email protected]',
])->execute();
$connection->createCommand()->insert('user_roles', ['role = "admin",
'user_id'=$user->id
])->execute();
$transaction->commit();
} catch(Exception $e) {
    $transaction->rollback();
}
0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments