Examples of transactions

//AR and rollback of transactions
public function actionCreate()
    {
        /** @var BaseActiveRecord $model */
        $model = new $this->modelClass('create');
 
        $this->performAjaxValidation($model);
 
        $model->attributes = Yii::app()->request->getParam($this->modelClass, array());
 
        if (Yii::app()->request->isPostRequest && !Yii::app()->request->isAjaxRequest) {
            $transaction = $model->getDbConnection()->beginTransaction();
            try {
                $model->save();
                $transaction->commit();
                $url = array('update', 'id' => $model->primaryKey);
                $this->redirect($url);
            } catch (Exception $e) {
                $transaction->rollback();
            }
        }
 
        $this->render('create', array('model' => $model));
    }
 
public function actionCreate()
    {
        /** @var BaseActiveRecord $model */
        $model = new $this->modelClass('create');
 
        $this->performAjaxValidation($model);
 
        $model->attributes = Yii::app()->request->getParam($this->modelClass, array());
 
        if (Yii::app()->request->isPostRequest && !Yii::app()->request->isAjaxRequest) {
            $transaction = $model->getDbConnection()->beginTransaction();
 
            // Сохраняем состояние объекта
            $transaction->storeModelStateForRollback($model);
 
            try {
                $model->save();
                $transaction->commit();
                $url = array('update', 'id' => $model->primaryKey);
                $this->redirect($url);
            } catch (Exception $e) {
                $transaction->rollback();
            }
        }
 
        $this->render('create', array('model' => $model));
    }
 
// check if transaction started
if(($transaction=$connection->getCurrentTransaction())===null)
   $transaction=$connection->beginTransaction();
try
{
   $connection->createCommand($sql1)->e xecute();
   $connection->createCommand($sql2)->e xecute();
   //.... other SQL executions
   $transaction->commit();
}
catch(Exception $e)
{
   $transaction->rollBack();
}

Leave a Comment

Fields with * are required.

Please enter the letters as they are shown in the image above.
Letters are not case-sensitive.