1.控制器中:
如果不涉及到数据库的就在控制器中。
empty($res['code']) ? $this->error($res['msg']) : $this->success($res['msg']);
抛出异常写法:
try{ $res = $Scoreflow->doaddscore($post); if(empty($res['code'])){ throw new \Exception($res['msg']); } $this->success($res['msg']);}catch(\Exception $e){ $this->error($e->getMessage());}
2.模型中:
所有关于数据库的操作都在模型里面做。
return['code' => 0|1,'msg' => '返回信息'];//回复格式统一,会比较好处理
模型中的回滚(需要用 self:: ,否则不起作用)
self::startTrans();try{ //符合条件修改状态 $exchangerecord_status = Exchangerecord::where('code',$code) ->update(['status' => '4']); //符合条件减库存 $goods_stock = Goods::where('id',$exchangerecord['ngzb_goods_id']) ->setDec('stock', 1); // 提交事务 self::commit();} catch (\Exception $e) { // 回滚事务 self::rollback(); return['code'=>0,'msg'=>'兑换失败'];}
来源:https://www.cnblogs.com/roseY/p/11016399.html