Transaction: A transaction is used to run a group of operations in single process. When you we run multiple query in single process, It will be used. If you get any problem, It will not complete successfully and also rollback the executed query.
Note
//Before use the Query Class, We have to add the following namespace
use yii\db\Query;
$connection = \Yii::$app->db;
beginTransaction()
In below example, We will create new user. After we created user will assign the role for that user. 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.
<php
$transaction = $connection->beginTransaction();
try {
$user_model=$connection->createCommand()
->insert('tbl_user', [
'name' => 'yii',
'status' => 1,
])->execute();
$connection->createCommand()
->insert('tbl_user_roles', [
'role' = "admin",
'user_id'= $user_model->id
])->execute();
//.....
$transaction->commit();
} catch(Exception $e) {
$transaction->rollback();
}
?>