try{ $this->user = D('User'); $this->user->startTrans(); //开始事务 $res = $this->user->Saveuser($where,$data); $res1 = $this->user->Saveuser($where,$data); if(!$res||!$res1){ throw new Exception('数据实例化失败'); } $this->user->commit(); //确认事务 }catch(Exception $e){ $this->user->rollback(); //回滚 }
/* * 添加酒店和房型 * */ public function insertAll($arr_hotel=array(),$arr_room=array()){ $model = new Model(); $model->startTrans(); $flag=false; $hid = $model->table(C('DB_PREFIX').'hotel')->add($arr_hotel); if( $hid && count($arr_room) ==0 ){//如果没有传入房型的信息则,直接提交数据 $flag=true; }else if( $hid && count($arr_room) >= 0){//存在对应房型信息,则添加对应的酒店编号,并处理提交 for($i=0 ; $i<count($arr_room) ; $i++){ $arr_room[$i]['hid'] = $hid; } $rid = $model->table(C('DB_PREFIX').'room')->addAll($arr_room); if( $rid ){ $model->commit(); $flag=true; } } if(!$flag){ $model->rollback(); }else{ $model->commit(); } return $flag; }
$Model = M(); $Model->startTrans(); $userRes = $Model->table('test_user')->add(['name'=>'admin']); $keyRes = $Model->table('test_key')->add(['key'=>'test']); $taskRes = $Model->table('test_task')->add(['task'=>'test']); if (userRes && $keyRes && $taskRes) $Model->commit(); else $Model->rollback();
批量事务
$document->startTrans(); foreach($list as $k=>$v){ // setField('value', $val); $isRight = $document->where(array('id'=>$v['id']))->setField('url',$name.'/'.$v['id'].'.html'); if(!$isRight){ $error[] = $isRight; }; }; if(count($error)){ $document->rollback(); $return['code'] = 0; $return['msg'] = '修改栏目文章链接失败'; exit(json_encode($return)); }; $document->commit();
$trans_result = true; $trans = M(); $trans->startTrans(); // 开启事务 try { // 异常处理 // 更新实施 $busbidList = M("busbid")->where($map)->select(); foreach($busbidList as $k => $v) { $map['id'] = $busbidList[$k]['id']; $result = M('busbid')->where($map)->data($data)->save(); if ($result === false) { throw new Exception(“错误原因”); } } } catch (Exception $ex) { $trans_result = false; // 记录日志 Log::record("== xxx更新失败 ==", 'DEBUG'); Log::record($ex->getMessage(), 'DEBUG'); } if ($trans_result === false) { $trans->rollback(); // 更新失败 $array['status'] = 0; } else { $trans->commit(); // 更新成功 $array['status'] = 1; }