<ASK> How to use Transaction in yii2?

hi all.

in yii2.

we want to use transaction.

how exactly it works in controller.




public function actionCreate()

    {

        $model = new Post();

        $transaction = $model->getDb()->beginTransaction();

        try {

            if ($model->load(Yii::$app->request->post()) && $model->save()) {

                $transaction->commit();

            } else {

                return $this->render('create', [

                    'model' => $model,

                ]);

            }

        } catch (Exception $e) {

            $transaction->rollBack();

            throw $e;

        }

    }



above code, is right or wrong?


    

public function actionUpdate($id)

    {

        $model = $this->findModel($id);

		$transaction = $model->getDb()->beginTransaction();

		try {

			if ($model->load(Yii::$app->request->post()) && $model->save()) {

				$transaction->commit();

				return $this->redirect(['view', 'id' => $model->id]);

			} else {

				return $this->render('update', [

					'model' => $model,

				]);

			}

        } catch (Exception $e) {

            $transaction->rollBack();

            throw $e;

        }

    }



above code, is right or wrong?


    

public function actionDelete($id)

    {	

		$model = $this->findModel($id);

		$transaction = $model->getDb()->beginTransaction();

		try {	

			$model->delete();

			$transaction->commit();

	    } catch (Exception $e) {

            $transaction->rollBack();

            throw $e;

        }		

        return $this->redirect(['index']);

    }

above code, is right or wrong?

thank you all for your help :)

I think the snippets are correct (just the first one is missing a return statement).

The only thing which is a bit problematic is that if the save call fails there is no explicit rollback. This happens then implicitly when the the db connection gets closed by the end of the script execution. I hope that is correct.

You can define the transaction in other ways too. See:

http://www.yiiframework.com/doc-2.0/yii-db-connection.html#transaction()-detail

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#transactional-operations

And another thing: if safe() or delete() executes only a single statement a transaction is not required.

1 Like