zoukankan      html  css  js  c++  java
  • yii2 事务添加

    在某些程序在执行的时候需要进行多个动作,而我们的业务要求是某个动作在执行错误的时候该进程所有的动作都不再执行,全部执行成功才算成功,否则就回到执行之前的状态,这就需要用到事务的处理。

    示例(基于YII框架):

            //支付单编号
            $paySn = CommonFun::makeRandSn($this->_memberId);
    
            $transaction = Yii::$app->db->beginTransaction();
            try{
    
                //格式化订单数据orders
                $order = $this->formatOrderData($cartGoods,$paySn);
    
                $orderId = $this->db::insert('orders',$order);
                if(!$orderId) throw new Exception('orders订单添加失败');
    
                $flag = $this->addOrderGoods($orderId,$order,$cartGoods['goods']);
                if(!$flag) throw new Exception('order_goods添加失败');
    
                $flag = $this->addOrderCommon($orderId,$order,$addressInfo,$extra);
                if(!$flag) throw new Exception('order_common添加失败');
    
                //更新库存,增加销售
                $flag = $this->updateGoodsStorage($cartGoods['goods']);
                if(!$flag) throw new Exception('库存更新失败');
    
                if($this->request('order_type')=='2' && $this->request('join_order_id')<=0)
                {
                    //创建拼团开团订单 这时默认拼团只能购买单个产品
                    if(!$this->createPintuanOpenOrder($cartGoods['goods'][0],$orderId))
                        throw new Exception("开团订单创建失败");
                }
                //更新优惠券
                if($extra['coupon_info']){
                    //更新优惠券
                    $where = ['id'=>$extra['coupon_info']['coupon_id']];
                    if(!Coupons::updateAll(['state'=>'2','update_time'=>time()],$where))
                        throw new Exception("优惠券更新失败");
                }
                 //上面动作全部有效才提交,否则回滚
                $transaction->commit();
                return array('pay_sn'=>$paySn,'order_id'=>$orderId);
    
            }catch(Exception $e)
            {
                $transaction->rollBack();
                $this->error('下单失败:'.$e->getMessage());
            }
  • 相关阅读:
    contest hunter5105 Cookies
    bzoj2599: [IOI2011]Race
    poj1741 Tree
    bzoj2527: [Poi2011]Meteors
    bzoj3673: 可持久化并查集 by zky&&3674: 可持久化并查集加强版
    bzoj2741: 【FOTILE模拟赛】L
    bzoj3110: [Zjoi2013]K大数查询
    bzoj1901: Zju2112 Dynamic Rankings
    bzoj2821: 作诗(Poetize)
    poj1417 True Liars
  • 原文地址:https://www.cnblogs.com/jackzhuo/p/12982157.html
Copyright © 2011-2022 走看看