Yii Framework 2 : Transaction

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.


//Before use the Query Class, We have to add the following namespace

use yii\db\Query;
$connection = \Yii::$app->db;


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.

    $transaction = $connection->beginTransaction();
    try {
                ->insert('tbl_user', [
                        'name' => 'yii',
                        'status' => 1,

                ->insert('tbl_user_roles', [
                    'role' = "admin",
                    'user_id'= $user_model->id
    } catch(Exception $e) {


Leave a Reply

Your email address will not be published. Required fields are marked *