Hello!
I am using a transaction in my action:
public function actionCreate()
{
$model_1 = new Model_1('somescenario');
$model_2 = new Model_2('somescenario2');
$model_3 = new Model_3();
$model_4 = new Model_4('somescenario3');
$model_5 = new Model_5();
$transaction = $model_1->getDbConnection()->beginTransaction();
try
{
if(isset($_POST['Model_1'], $_POST['Model_3'], $_POST['Model_3'],
$_POST['Model_4']))
{
$model_1->attributes = $_POST['Model_1'];
$model_2->attributes = $_POST['Model_2'];
$model_3->attributes = $_POST['Model_3'];
$model_4->attributes = $_POST['Model_4'];
$validate = $model_1->validate();
$validate = $model_2->validate() && $validate;
$validate = $model_3->validate() && $validate;
$validate = $model_4->validate() && $validate;
$validate = $model_5->validate() && $validate;
if($model_1->save())
{
$model_4->id_tb_1 = $model_1->id;
$model_2->id_tb_1 = $model_1->id;
$model_3->id_tb_1 = $model_1->id;
if($model_4->save() && $model_2->save() && $model_3->save())
{
if(isset($_POST['model_5']))
{
foreach($_POST['model_5']
['id'] as $id)
{
$model_6 = new Model_6();
$model_6->id = $id;
$model_6->id = $model_1->model_1_relation->id;
$model_6->save();
}
}
$model_2->createDatabaseRole($model_2->username);
$transaction->commit();
$this->redirect(array('userIndex'));
}
else
throw new CHttpException(404,
Yii::t('message', 'The specified model cannot be saved'));
}
else
throw new CHttpException(404,
Yii::t('message', 'The specified model cannot be saved'));
}
else
throw new CHttpException(404,
Yii::t('message', 'The specified POST cannot be found'));
}
catch(Exception $e)
{
$transaction->rollback();
}
}
But if I generate an exception after $model_1->save(), [color="#FF0000"]the data from the $model_1 still in the database[/color]. I generated an exception and looked at the database log. It says that the transaction started and rolled back:
LOG: statement: BEGIN
LOG: statement: SET NAMES 'utf8'
LOG: statement: SELECT 1 FROM "tb_2" "t" WHERE "t"."username"='thejames' LIMIT 1
LOG: statement: SET NAMES 'utf8'
LOG: statement: INSERT INTO "tb_1" ("...", "...", "...", "...", "...", "...", "...") VALUES ('The James', 'The James Bond', NULL, NULL, NULL, NULL, NULL)
LOG: execute <unnamed>: SELECT CURRVAL($1)
DETAIL: parameters: $1 = 'seq_tb_1'
LOG: statement: SET NAMES 'utf8'
LOG: statement: INSERT INTO "tb_4" ("...", "...", "...", "...", "...", "...", "...", "id") VALUES (NULL, '..', NULL, NULL, NULL, NULL, NULL, 0)
ERROR: insert or update on table "tb_4" violates foreign key constraint "tb_4_id_fkey"
DETAIL: Key (id)=(0) is not present in table "tb_1".
STATEMENT: INSERT INTO "tb_4" ("...", "...", "...", "...", "...", "...", "...", "id_1") VALUES (NULL, 'SP', NULL, NULL, NULL, NULL, NULL, 0)
LOG: statement: ROLLBACK
I’m using PostgreSQL 9.2.4 and Yii framework 1.1.13