where('del',0)->select(); } //获取到积分的商品列表 public static function goodslist($clsssId){ $where=[ 'brand_id'=>$clsssId, 'del'=>0 ]; $goods = Db::name('printer_goods') ->where($where) ->select(); foreach($goods as &$item){ $item['images']=UrlServer::getFileUrl($item['images']); } return $goods; } //根据ID获取到积分商品 public static function goodsIofo($id){ $data=Db::name('printer_goods')->where('id',$id)->find(); $data['images']=UrlServer::getFileUrl($data['images']); return $data; } /** * 积分商品下单(扣减积分并生成订单) * @param array $data ['id','name','price','user_id','number'(可选)] * @return array */ public static function goodsSub($data){ if(empty($data) || !is_array($data)){ return ['code'=>0,'msg'=>'参数错误']; } // 基础校验 if(empty($data['id']) || empty($data['user_id']) || !isset($data['price'])){ return ['code'=>0,'msg'=>'参数不完整']; } $number = isset($data['number']) && intval($data['number'])>0 ? intval($data['number']) : 1; $price = floatval($data['price']); $needIntegral = $price * $number; Db::startTrans(); try{ // 加锁读取用户积分 $user = Db::name('user')->where('id',$data['user_id'])->lock(true)->find(); if(!$user){ throw new Exception('用户不存在'); } if($user['user_integral'] < $needIntegral){ throw new Exception('积分不足'); } $orderData = [ 'name' => $data['name'] ?? '', 'goods_id' => $data['id'], 'price' => $price, 'number' => $number, 'user_id' => $data['user_id'], 'create_time' => time(), 'address_id' => $data['addressId'], 'state' => 1 ]; $insert = Db::name('printer_order')->insert($orderData); if(!$insert){ throw new Exception('下单失败'); } // 扣减积分 Db::name('user') ->where('id',$data['user_id']) ->setDec('user_integral', $needIntegral); Db::commit(); return ['code'=>1,'msg'=>'兑换成功']; }catch (\Exception $e){ Db::rollback(); return ['code'=>0,'msg'=>$e->getMessage()]; } } //获取积分订单 public static function orderList($userId, $state = null) { $order = new OrderPoints(); $query = $order->with([ 'address' => function($query){ $query->where('del',0)->field('id,address'); }, 'pointsGoods' => function($query){ $query->where('del',0)->field('id,images'); } ])->where('user_id', $userId); // 如果传了state参数,才添加state条件,否则查询全部 if($state !== null && $state !== ''){ $query = $query->where('state', $state); } $orderArray = $query->paginate(10); return $orderArray; } }