作业

来源:10-6 商品列表页API开发

CHUNALAI

2020-04-25

app\api\controller\Category.php

/**
     * 请求格式api/category/search/51
     * 商品列表页面中 按栏目检索的内容
     * @return \think\response\Json
     */
    public function search() {
        $id = input("param.id", 0, "intval");
        $result = (new CategoryBis())->search($id);
        return show(config("status.success"), "ok", $result);
    }

    /**
     * 获取子分类  category/sub/2
     * @return \think\response\Json
     */
    public function sub() {
        $id = input("param.id", 0, "intval");
        $result = (new CategoryBis())->sub($id);
        return show(config("status.success"), "ok", $result);
    }

app\common\business\Category.php

public function search($id) {
        try {
            $result = [];
            $res = $this->model->getCategoryId($id)->toArray();
            // 获取path值
            $categoryPath = explode(",", $res[0]['path']);
            //获取一级分类名称
            $categoryOne = array_slice($categoryPath, 0, 1);
            $result["name"] = $this->model
                ->getCategoryId($categoryOne, "name")
                ->toArray()[0]['name'];
            //获取定位点focus_ids
            $result["focus_ids"] = array_slice($categoryPath, 1);
            foreach ($result['focus_ids'] as $key => $value) {
                $result['focus_ids'][$key] = intval($value);
            }
            //获取子分类list
            array_pop($categoryPath);
            if (count($categoryPath) == 0) { //如果是一级分类则获取他下面的二级分类
                $result['list'][0] = $this->model
                    ->getNormalByPid($categoryOne, "id, name")
                    ->toArray();
            } else { //如果是二级和三级分类,则获取同pid的所有分类
                foreach ($categoryPath as $k => $v) {
                    $result['list'][$k] = $this->model
                        ->getNormalByPid($v, "id, name")
                        ->toArray();
                }
            }
        } catch (\Exception $e) {
            //记录日志
            trace("Category-search-SeverException".$e->getMessage(), "error");
            return Arr::search();
        }
        return $result;
    }

    public function sub($id) {
        try {
            $result =  $this->model->getNormalByPid($id, "id,name")->toArray();
        } catch (\Exception $e) {
            //记录日志
            trace("Category-sub-SeverException".$e->getMessage(), "error");
            return [];
        }
        return $result;
    }
写回答

2回答

qq_听得见的安静_0

2020-05-06

path值   在mall_category 表里是没有的吧,是你自己在添加分类的时候加上去的吗

0
3
singwa
回复
CHUNALAI
赞赞赞
2020-05-06
共3条回复

singwa

2020-04-27

赞赞赞

0
0

全流程开发 TP6.0实战高并发电商服务系统

一课就能掌握TP6.0基础及运用,打造完整高并发的电商后端项目

1458 学习 · 1310 问题

查看课程