CDbTransaction In Yii

To use transaction, do like the following: Using transaction function commit and rollback, We can avoid the errors on db insert.

beginTransaction With Model


$transaction = Yii::app()->db->beginTransaction();
try {
    $model=new User;
    ...............
    ...............
    $model->save();
    $transaction ->commit();
} catch (Exception $error) {
    $transaction ->rollback();
    throw $error;
}

beginTransaction With createCommand


<?php
    $transaction=$connection->beginTransaction();
    try
    {
        $connection->createCommand($sql1)->execute();
        $connection->createCommand($sql2)->execute();
        //.... other SQL executions
        $transaction->commit();
    }
    catch(Exception $e)
    {
        $transaction->rollback();
    }
?>