7

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?

rob006
  • 21,383
  • 5
  • 53
  • 74
hamedkh
  • 909
  • 3
  • 18
  • 35

1 Answers1

19

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.)
} 
rob006
  • 21,383
  • 5
  • 53
  • 74
Benjamin Kaiser
  • 2,177
  • 22
  • 24