简体   繁体   English

Yii交易不会回滚

[英]Yii transaction doen't roll back

Yii transaction doesn't roll back in the below sample code and records saved in DB: Yii事务不会回滚到下面的示例代码和保存在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 .. 谢谢

The right way to use transactions is to use them with the try-catch construction. 使用事务的正确方法是将它们与try-catch构造一起使用。 In your example I think that the problem comes because you didn't do the commit ($transaction->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! 编辑: $ model-> save()不会抛出异常,所以你需要抛出它!

Make sure that the storage engine for your tables is InnoDB. 确保表的存储引擎是InnoDB。 I believe it is the only transaction-safe engine available by default. 我相信它是默认情况下唯一可用的事务安全引擎。 More on available engines in the mysql docs 有关mysql文档中可用引擎的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM