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) {

  • Ben

    Could you please explain what is a transaction? Thank you

    • m bala

      updated but not much

  • Guntur Budi Herwanto
  • Nicolás Ignacio Leone

    Hello, I’m from Agentina, I’m interested in the subject since I’m trying. Here it explains how to configure them automatically to be transactional, http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#transactional-operations, but I do not know how to implement the part that says:

    Class Customer extends ActiveRecord
    Public function transactions ()
    return [
    ‘Admin’ => self :: OP_INSERT,
    ‘Api’ => self :: OP_INSERT | Self :: OP_UPDATE | Self :: OP_DELETE,
    // the above is equivalent to the following:
    // ‘api’ => self :: OP_ALL,

    In addition I read that transactions can bring deadlocks conflicts …. it is better to use optimistic locks ….

    Can someone give me a hand with that subject?

    Greetings and thanks.

  • Raffaele TOSTI

    php associative array syntax is wrong on the second insert, it should be:

    ‘role’ => “admin”,
    ‘user_id’ => $user_model->id