thinkphp5
可以不用 try {} catch (\Exception $e) {} 可以直接使用Db::startTrans();Db::commit();Db::rollback();
if (!$updateMoney) {Db::rollback();return V(0, '出错,请重试');}注意 使用tp5事务时 不要用db() 要用Db::name 或者 Db::table// 开启事务Db::startTrans();try {// 开启事务 Db::startTrans(); //写在这个位置也可以//任意一个表写入失败都会抛出异常://比如加一个判断if (false) {throw new \Exception('操作失败'); //抛出错误}//根据 订单id 和门店 id 去判断 有没有分配分拣员$where_a['id'] = $post_data['order_id'];
// $where_a['store_id'] = $post_data['store_id'];$find_storer = Db::name('shopro_order')->where($where_a)->value('storer_id');if(!$find_storer){ //没有分配的分拣员//先去判断有没有分拣员上班$storer_info = $this->get_assign_storer();if(!$storer_info){throw new \Exception('无分拣员接单');}//第一步要去获取分拣员的数据 读取缓存数据$storer_id = $storer_info['id']; //分拣员id//先去分配分拣员$where_storer['order_id'] = $post_data['order_id'];$update_storer['storer_id'] = $storer_id;$re['storer'] = Db('shopro_order_son')->where($where_storer)->update($update_storer);//主表$where_order['id'] = $post_data['order_id'];$update_order['storer_id'] = $storer_id;$update_order['storer_state'] = 1;$update_order['storer_assign_time'] = date('Y-m-d H:i:s',time());$re['order'] = Db('shopro_order')->where($where_order)->update($update_order);}//去修改子订单表 clz_shopro_order_son$where_son['order_id'] = $post_data['order_id'];$where_son['store_id'] = $post_data['store_id'];$update_son['store_state'] = 2;$update_son['storer_state'] = 1;$update_son['store_stockup_time'] = date('Y-m-d H:i:s',time());$re['son'] = Db('shopro_order_son')->where($where_son)->update($update_son);//任意一个表写入失败都会抛出异常:if (in_array('0', $re)) { // if ($res1==0 || $res2==0 ||$res3 == 0) {throw new \Exception('操作失败');//抛出错误}// 提交事务Db::commit();$this->return_data(1, '操作成功', true);} catch (\Exception $e) {// 回滚事务 如获取到异常信息,对所有表的删、改、写操作,都会回滚至操作前的状态:Db::rollback();$msg = $e->getMessage();$this->return_data(0, $msg, true);}、、、、、、、、try {//开启事物Db::startTrans();$res1 = Db:name('frieslandtravel_apply')->insert($add_apply);$res2 = Db:name('frieslandtravel_apply_son')->insert($add_apply_son);//任意一个表写入失败都会抛出异常:if ($res1==0 || $res2==0) {throw new \Exception('操作失败');//抛出错误}// 提交事务Db::commit();exit_json( init_err(0, '操作成功') );} catch (\Exception $e) {// 回滚事务 如获取到异常信息,对所有表的删、改、写操作,都会回滚至操作前的状态:Db::rollback();exit_json( init_err(1, '操作失败') );}if ( !function_exists('init_err') ) {function init_err($err=1, $msg='未知错误', $data=null){return ['err' => $err,'msg' => $msg,'data' => $data,];}
}if ( !function_exists('exit_json') ) {/*** Desc:输出json字符串* Date:2021/1/31 14:55* Author: guanzy@huilan-online.com* --------------------------------* @param $data* --------------------------------*/function exit_json($data){exit( json_encode($data, 256) );}
}