Using transaction in a loop in Yii

被刻印的时光 ゝ 提交于 2019-12-12 11:16:37

问题


I have an array of active records and want to change some field of them with a loop in this manner:

$error = false;
foreach ($items as $item) {
    $item->is_paid = self::PENDING;
    $error = $error || !$item->save();
}
return $error;

What I want to do is to change the is_paid property for all of this items. If on fails, roll back the others. How can I use transaction to solve this problem?


回答1:


By a brief look here, I was able to find the transaction management in yii, something like the following should work for you:

$transaction = Yii::app()->db->beginTransaction();
try {
    foreach ($items as $item) {
        $item->is_paid = self::PENDING;
        $item->save();
    }
    $transaction->commit();
    // actions to do on success (redirect, alert, etc.)
} catch (Exception $e) {
    $transaction->rollBack();
    // other actions to perform on fail (redirect, alert, etc.)
} 


来源:https://stackoverflow.com/questions/15792019/using-transaction-in-a-loop-in-yii

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!