PHP TP 事务、Try Catch REPLACE INTO

注意事项:

  1、事务的开启关闭,以及回滚;

  2、try。catch的作用在于防止一些未知的异常抛出

  3、REPLACE INTO 语句使用原生(后台表必须带主键,没有更新会出问题滴

  4、简要说下三者的区别:insert into 最普遍的插入,如果表中存在主键相同的数据,执行会报错。

             replace into 如果表中存在主键相同的数据则根据主键修改当前主键的数据,反之则插入(存在就修改,反之插入

             insert ignore  如果表中存在主键相同的数据不在插入该条数据,反之则插入(存在则忽略,反之插入

  5、借鉴网址:https://www.cnblogs.com/fillt/archive/2018/05/31/9118238.html

    $transaction = M();
        $transaction->startTrans();//开启事务

        try {

            //$updateList=[];
            $insertList=[];
            foreach($dateList as $kl=>$vl) {

                $save['roomPrice']['date']=$vl;
                $insertList[]=$save['roomPrice'];

                //方法一 01:正常的TP 插入,先判断存在,再判断插入还是更新
                /*//判断更新还是插入,分配到不同数组
                $checkCount=count($roomPriceM->where(['room_id'=>$save['roomPrice']['room_id'],'date'=>$vl])->select());

                if($checkCount==0){// 此房间不存在该日期价格--插入
                    $insertList[]=$save['roomPrice'];
                }else{// 更新
                    $updateList[]=$save['roomPrice'];
                }*/
            }

            //方法二,原生插入REPLACE INTO
            //获取字段名
            $fields='`'.implode("`,`", array_keys($insertList[0])).'`';

            foreach ( $insertList as $kr=>$vr){

                $values='';//每次置空
                foreach($vr as $kv=>$vv){
                    $values[]=$vv;

                }

                //变量值重组
                $valuesStr='"'.implode("\",\"", $values).'"';
                //原生语句
                $sqlStr='REPLACE INTO `hotel_room_prices` ('.$fields.') VALUES ('.$valuesStr.');';
                //运行原生语句
                $re=M()->execute($sqlStr);
                Ptn::filebug('影响数据条数  roomPrices表:'.$re, 'roomPrices_Update/InsertInfo');

            }


            //方法一 02:正常的TP 插入,先判断存在,再判断插入还是更新
            /*if(!empty($insertList)){
                $resRoom = $roomPriceM->addAll($insertList);
                Ptn::filebug('插入影响数据条数  roomPrices表:'.$resRoom, 'roomPrices_InsertInfo');
            }
            if(!empty($updateList)){
                foreach($updateList as $ku=>$vu){
                    $resRoom = $roomPriceM->where(['room_id'=>$vu['room_id'],'date'=>$vu['date']])->save($updateList);
                    Ptn::filebug('更新影响数据条数  roomPrices表:'.$resRoom, 'roomPrices_UpdateInfo');
                }

            }*/

            $transaction->commit();//关闭事务

            $code = 0;
            $msg = '更新成功';

        }catch (\Exception $e){

            $transaction->rollback();//事务回滚
            return $e->getMessage();

        }

猜你喜欢

转载自www.cnblogs.com/brucebear/p/10108015.html