Transaction On Multiple Ar Problem

I have a problem with this code when it failed after throwing an exception.

Basically, if $address->save() and $customer->save() is successful and an if statement after that throws an Exception, it did roll back but after another call to this controller, this is the DB Command in Application Log:

  • Address.update()

  • Address.updateByPk()

  • Customer.update()

  • Customer.updateByPk()

There’s no record on the DB itself (because its supposed to have rolled back) but the AR itself is trying to update rather than insert a new record which means that AR is saved somehow but DB is rolled back.

What I want is to have AR rolled back as well so the executed DB Command will be:

  • Address.insert()

  • Customer.insert()


                    

$trans = Yii::app()->db->beginTransaction();

                    try {

                        

                        if($address->save()) {

                            throw new CException('Address Transaction Failed');

                        }

                        

                        $customer->delivery_address_id = $address->id;

                        if($customer->save()) {

                            throw new CException('Customer Transaction Failed');

                        };

                        

                        $order->status = 'pending';

                        $order->customer_id = $customer->id;

                        $order->payment_id = $payment->id;


                        if(!$order->save()) {

                            throw new CException('Order Transaction Failed');

                        }

                        $result = $order->lockStock();

                        // if error on lockStock()

                        if(empty($result)) {

                            throw new CException('result from lockStcok is empty');

                        }

                        $order->subtotal = $result['totalPrice'];

                        $order->total_quantity = $result['totalQuantity'];

                        if(!$order->save()) {

                            throw new CException('Transaction Failed');

                        }

                        

                        $trans->commit();

                        $this->redirect(array('summary'));

                    } catch (Exception $ex) {

                        Yii::trace(var_dump($ex));

                        $trans->rollback();

                    }