How to implement Commit rollback?

Hi Everyone,

I have a table and generate model and normal crud pages. While saving data using a form, I would like to save some data in another table as well.

I am writing the code as below. Does it follow commit roll back functionality?

Suppose my first model is saved and something went wrong and another sql query not executed. Then will it rollback in this scenario?

If no, How can I achieve it?




if($model->save())

            {

									

                if (Yii::app()->request->isAjaxRequest)

                {

							

                    echo CJSON::encode(array(

                        'status'=>'success', 

                        'div'=>"You successfully contributed fund to this event"

                        ));

						

			//Adding Debit Transaction into FundNano

			$command1 = Yii::app()->db->createCommand('INSERT INTO fund_nano ( USER_ID, AMOUNT, AMT_INDICATOR, EVENT_ID, STATUS ) VALUES ( '.$model->USER_ID.', '.$model->AMOUNT.', "DR", '.$model->ORG_EVENT_ID.', "FUNDED AN EVENT" )');

			//$command1->bindValue(':sum', $sum);

			$nanoPass = $command1->execute();

		    //End

			

				

				

                    exit;               

                }

                else

				    

                   $this->redirect(array('view','id'=>$model->id));

            }

        }




Thank you in advance

looks like you haven’t read the documentation… - http://www.yiiframework.com/doc/guide/1.1/en/database.ar#using-transaction-with-ar

Hi mdomba,

I read that article. But still I have doubt on my knowledge. I created as follow. Could you please check whether the following is implementing commit roll back process?




public function actionCreate()

	{

		$model=new FundGrantedEvent;


		

		if(isset($_POST['FundGrantedEvent']))

		{

			$model->attributes=$_POST['FundGrantedEvent'];

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

			try

			{

			$model->save();

			$transaction->commit();

			$this->redirect(array('view','id'=>$model->GRANT_ID));

			}

			catch(Exception $e)

			{

				$transaction->rollBack();

			}

				

		}


		$this->render('create',array(

			'model'=>$model,

		));

	}



Yes, it should work, but here you are using only one table to save… so in this case the transaction is not needed…

the transactions are needed if you need to save more tables together… so that all table are saved… .or none…

This one is correct.

Anyway consider that:

If you don’t do explicit commit, the transaction will be rollbacked anyway, so it would work correctly even without:


 $transaction->rollBack();

If in your save() you are just saving the model (and not changing anywere else the database) the transaction can be avoided, as you are doing a single transaction that is already atomic.

Thank you mdomba & Zaccaria

Thanx It helped me out/