request->param('id/d'); if (!$id) { $this->error('参数错误'); } $row = (new GoodsModel())->with([ 'Sku', 'Comment' => function ($query) { $query->relation([ 'reply' => function ($user) { $user->with([ 'manage' => function ($u) { $u->field('id,nickname'); } ]); } ])->where('status', 'normal')->where('pid', 0)->field('id,goods_id,content,star,user_id,images,comments,createtime')->with([ 'User' => function ($u) { $u->field('id,nickname,avatar'); } ])->order('createtime', 'desc')->limit(10); } ])->whereIn('status',[GoodsEnum::STATUS_ON_SALE,GoodsEnum::STATUS_SOLD_OUT])->where('id', $id)->find(); if (!$row) { $this->error('未找到该商品'); } // 浏览次数 $row->setInc('views'); //收藏 if ($this->auth->isLogin()) { $row->is_collect = !!(Collect::where('user_id', $this->auth->id)->where('goods_id', $id)->where('status', 1)->find()); } else { $row->is_collect = false; } $row->sku_spec = SkuSpecService::getGoodsSkuSpec($id); // 要处理规格的图片 // 这个错误是因为 $row->sku_spec 是一个重载属性(通过魔术方法 __get() 获取),不能直接通过引用修改。我们需要先将其转换为普通数组,处理后再赋值回去。 if (!empty($row->sku_spec)) { $skuSpecData = $row->sku_spec; // 先转换为普通数组 foreach ($skuSpecData as $key => &$item) { if (!empty($item['sku_value'])) { foreach ($item['sku_value'] as $k => &$v) { $v['image'] = empty($v['image']) ? '' : cdnurl($v['image'], true); } } } $row->sku_spec = $skuSpecData; // 处理完后重新赋值 } // //服务保障 $row->guarantee = $row->guarantee_ids ? Guarantee::field('id,name,intro')->where('id', 'IN', $row->guarantee_ids)->where('status', 'normal')->select() : []; //属性 $row->attributes = AttributeValue::getAttributeList($row->attribute_ids); //好评度 $row->favor_rate = Comment::degree($id); //评论 $comment = collection($row->comment)->toArray(); foreach ($comment as &$item) { if ($item['user']) { $item['user']['avatar'] = cdnurl($item['user']['avatar'], true); } } $row->setRelation('comment', $comment); unset($item); //优惠券 // $conditions = CouponCondition::getGoodsCondition($id, $row->category_id, $row->brand_id); // $sql = "condition_ids IS NULL OR condition_ids=''"; // foreach ($conditions as $key => $item) { // $sql .= " OR FIND_IN_SET('{$item['id']}',condition_ids)"; // } // $couponList = Coupon::field('id,name,result,result_data,allow_num,begintime,endtime,use_times,received_num,give_num,mode,createtime') // ->where($sql) // ->where('is_open', 1) // ->where('is_private', 'no') // ->where('endtime', '>', time()) // ->select(); // //已经登录,渲染已领的优惠券 // $coupon_ids = []; // if ($this->auth->isLogin()) { // $coupon_ids = UserCoupon::where('user_id', $this->auth->id)->column('coupon_id'); // } // foreach ($couponList as $key => &$item) { // Coupon::render($item, $coupon_ids); // $item->hidden(['received_num', 'give_num', 'condition_ids']); // } // $row->coupon = $couponList; $row->visible(explode(',', 'id,title,type,spec_type,sub_title,category_ids,price,lineation_price,sales,views,is_hot, image,content,images,sku_spec,sku,comment,is_collect,guarantee,attributes,favor_rate,coupon')); $row = $row->toArray(); $row['content'] = \app\common\library\Service::formatTplToUniapp($row['content']); //查询折扣信息 以及倒计时 $row['discount_info'] = DiscountService::getGoodsDiscountDetail($row['id']); $this->success('获取成功', $row); } public function getGoodsCustomizedSpec() { $id = $this->request->param('id/d'); if (!$id) { $this->error('参数错误'); } $row = (new GoodsModel()) ->field('id,title,sub_title,type,category_ids,price,lineation_price,image') ->whereIn('status',[GoodsEnum::STATUS_ON_SALE,GoodsEnum::STATUS_SOLD_OUT]) ->where('id', $id)->find(); if (!$row) { $this->error('未找到该商品'); } $row->sku_spec = SkuSpecService::getGoodsSkuSpec($id,2); // 要处理规格的图片 // 这个错误是因为 $row->sku_spec 是一个重载属性(通过魔术方法 __get() 获取),不能直接通过引用修改。我们需要先将其转换为普通数组,处理后再赋值回去。 if (!empty($row->sku_spec)) { $skuSpecData = $row->sku_spec; // 先转换为普通数组 foreach ($skuSpecData as $key => &$item) { if (!empty($item['sku_value'])) { foreach ($item['sku_value'] as $k => &$v) { $v['image'] = empty($v['image']) ? '' : cdnurl($v['image'], true); } } } $row->sku_spec = $skuSpecData; // 处理完后重新赋值 } $this->success('获取成功', $row); } //列表 public function lists() { $param = $this->request->param(); // 增加验证器处理 $validate = new \app\api\validate\Goods(); if (!$validate->scene('lists')->check($param)) { $this->error($validate->getError()); } $pageSize = $param['pageSize'] ?? 10; $orderby = $param['orderby'] ?? 'weigh'; $orderway = $param['orderway'] ?? 'desc'; // 映射字段 $orderby weigh,sales,price,views,comments,created_at $orderbyMap = [ 'weigh' => 'weigh', 'sales' => 'sales', 'views' => 'views', 'comments' => 'comments', 'created_at' => 'createtime', ]; $query = GoodsModel::where(function ($query) use ($param) { $query->where('status',GoodsEnum::STATUS_ON_SALE); //关键词 if (isset($param['keywords']) && !empty($param['keywords'])) { $query->where('title|keywords', 'like', '%' . $param['keywords'] . '%'); $log = \app\common\model\SearchLog::getByKeywords($param['keywords']); if ($log) { $log->setInc("nums"); } else { \app\common\model\SearchLog::create(['keywords' => $param['keyword'], 'nums' => 1, 'status' => 'hidden']); } } //分类 if (isset($param['category_id']) && !empty($param['category_id'])) { $categoryIds = []; // 获取子集 $categoryChildIds = \app\common\model\Category::getCategoryChildrenIds($param['category_id']); $categoryIds = array_merge($categoryChildIds, [$param['category_id']]); $query->where(function ($query) use ($categoryIds) { // 所有子分类使用 find_in_set or 匹配,亲测速度并不慢 foreach ($categoryIds as $key => $category_id) { $query->whereOrRaw("find_in_set($category_id, category_ids)"); } }); } //属性 if (isset($param['attributes']) && !empty($param['attributes'])) { $query->where('id', 'IN', \app\common\model\GoodsAttr::getGoodsIds($param['attributes'])); } //品牌 if (isset($param['brand_id']) && !empty($param['brand_id'])) { $query->where('brand_id', 'IN', $param['brand_id']); } //价格 if (isset($param['price']) && !empty($param['price'])) { $priceArr = explode('-', $param['price']); if (count($priceArr) == 2) { if (isset($priceArr[0])) { $priceArr[0] = (float)$priceArr[0]; } if (isset($priceArr[1])) { $priceArr[1] = (float)$priceArr[1]; } $query->where('price', 'BETWEEN', $priceArr); } } }); if (!empty($orderby) && !empty($orderway)) { $orderby = $orderbyMap[$orderby] ?? 'weigh'; $query = $query->order("{$orderby} {$orderway}"); } $list = $query->paginate($pageSize); foreach ($list as $item) { $item->visible(explode(',', 'id,title,image,price,sales,views,description,lineation_price,is_hot,createtime')); } $this->success('', $list); } // 根据分类顶级ID 查询子集 和对应的商品 public function getCategoryGoods() { $param = $this->request->param(); $categoryId = $param['category_id'] ?? 0; // 验证器 $validate = new \app\api\validate\Goods(); if (!$validate->scene('getCategoryGoods')->check($param)) { $this->error($validate->getError()); } // 查询子集分类信息 $categoryChildIds = CategoryService::getCategoryChildrenIds($categoryId); // 查询所有直接子分类 $children = []; foreach (CategoryService::getCategoryByIds($categoryChildIds) as $cat) { if (isset($cat['pid']) && $cat['pid'] == $categoryId) { $children[] = $cat; } } // 获取所有直接子分类ID $childrenIds = array_column($children, 'id'); // 一次性查出所有相关分类下的所有商品(不分页) $allGoods = GoodService::getCategoryGoods($childrenIds); // 不分页查全部 // 按分类分组,每组只保留4个 $goodsByCategory = []; foreach ($allGoods as $goods) { if (empty($goods['category_ids'])) continue; $goodsCatIds = explode(',', $goods['category_ids']); foreach ($goodsCatIds as $catId) { $catId = intval($catId); if (in_array($catId, $childrenIds)) { if (!isset($goodsByCategory[$catId])) $goodsByCategory[$catId] = []; if (count($goodsByCategory[$catId]) < 4) { $goodsByCategory[$catId][] = $goods; } } } } // 组装返回 $arrReturn = []; foreach ($children as $item) { $item['goods'] = $goodsByCategory[$item['id']] ?? []; $arrReturn[] = $item; } $this->success('', $arrReturn); } //获取小程序码 public function getWxCode() { $goods_id = $this->request->post('goods_id'); $version = $this->request->post('version', 'release'); if (empty($goods_id)) { $this->error('参数错误'); } $user_id = ''; if ($this->auth->isLogin()) { $user_id = $this->auth->id; } $resource = ''; $fileStream = (new \app\common\library\message\Mini)->getWxCodeUnlimited([ 'scene' => "invite_id={$user_id}&goods_id={$goods_id}", 'env_version' => $version, //要打开的小程序版本。正式版为 release,体验版为 trial,开发版为 develop 'page' => 'pages/goods/detail', 'check_path' => false ]); if (is_null(json_decode($fileStream))) { try { $img = imagecreatefromstring($fileStream); ob_start(); imagepng($img); $resource = ob_get_clean(); } catch (\Exception $e) { \think\Log::write($e->getMessage()); $this->error("获取微信二维码失败!"); } } else { $config = get_addon_config('shop'); if ($config['wxapp']) { $localFile = ROOT_PATH . 'public' . $config['wxapp']; if (is_file($localFile)) { $resource = file_get_contents($localFile); } else { $resource = Http::get(cdnurl($config['wxapp'], true)); } } if (config('app_debug')) { Log::write($fileStream); } } if (!$resource) { Log::write($fileStream); $this->error("获取二维码失败!"); } $base64_data = base64_encode($resource); $base64_file = 'data:image/jpg;base64,' . $base64_data; $this->success('获取成功', $base64_file); } }