天天看點

YII中使用事務

$transaction= Yii::app()->db->beginTransaction();//建立事務

$transaction->commit();//送出事務

$transaction->rollback();//復原事務

//使用事務,操作如果失敗,則復原
            $transaction=Yii::app()->db->beginTransaction();
            try{
                $orders_detial=  new TblOrderDetial();
                $orders->orders_sn=$orders_sn=date('ymd-',$time).rand(1000,9999);
                $orders->consignee=$_GET['consignee'];
                $orders->shipping_id=$_GET['shipping'];
                $orders->pay_id=$_GET['payment'];
                $orders->goods_amount=$cart->getPrice();
                $orders->add_time=date('Y-m-d H:I',$time);
                $orders->address=$_GET['address'];
                $orders->mobile=$_GET['mobile'];

                $orders->save();

                $orders_id=$orders->attributes['orders_id'];

                //讀取購物車内的資訊,寫入order_detial表中
                $items=$cart->items();
                $succ=array();
                foreach($items as $k=>$v){
                    $detialModel=new TblOrderDetial();
                    $detialModel->orders_id=$orders_id;
                    $detialModel->goods_id=$k;
                    $detialModel->goods_name=$v['name'];
                    $detialModel->shop_price=$v['shop_price'];
                    $detialModel->goods_number=$v['num'];
                    if($temp=$detialModel->save()){
                        $succ[]=$temp;
                    }
                }
                if($cart->cnt()==count($succ)){
                    //如果入庫的數量等于購物車裡面的數量,則復原
                    $transaction->commit();
                }
            }//try end
            catch(Exception $e){
                $transaction->rollback();
            }