Reputation: 43
Yii transaction doesn't roll back in the below sample code and records saved in DB:
$transaction = Yii::app()->db->beginTransaction();
$mode_1 = new Orders;
$mode_1->id_order = 3333;
$mode_1->AWB = 3333;
$mode_2 = new Orders;
$mode_2->id_order = 4444;
$mode_2->AWB = 4444;
$mode_2->save();
$mode_1->save();
$transaction->rollback();
any Idea? .. thanks
Upvotes: 3
Views: 5345
Reputation: 876
The right way to use transactions is to use them with the try-catch construction. In your example I think that the problem comes because you didn't do the commit ($transaction->commit()).
$transaction = Yii::app()->db->beginTransaction();
try {
if (!$model->save()) {
throw new Exception('Model cannot be saved.');
}
if (!$anothermodel->save()) {
throw new Exception('Anothermodel cannot be saved.');
}
$transaction->commit();
} catch (Exception $e) {
$transaction->rollback();
}
EDIT: $model->save() doesn't throw Exception, so you need to throw it!
Upvotes: 13
Reputation: 396
Make sure that the storage engine for your tables is InnoDB. I believe it is the only transaction-safe engine available by default. More on available engines in the mysql docs
Upvotes: 6