소스 검색

8-13前端分类接口返回,可无限极

Home 4 년 전
부모
커밋
8b6b865dfc
3개의 변경된 파일61개의 추가작업 그리고 16개의 파일을 삭제
  1. 23 0
      app/api/controller/Category.php
  2. 29 0
      app/common/lib/Arr.php
  3. 9 16
      app/common/model/mysql/Category.php

+ 23 - 0
app/api/controller/Category.php

@@ -0,0 +1,23 @@
+<?php
+
+
+namespace app\api\controller;
+
+use app\common\business\Category as CategoryBusiness;
+use app\common\lib\Arr;
+
+class Category extends ApiBase
+{
+    /**
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\DbException
+     * @throws \think\db\exception\ModelNotFoundException
+     */
+    public function index()
+    {
+        // 获取所有分类的内容
+        $categorys = (new CategoryBusiness())->getNormalCategory();
+        $result = Arr::getTree($categorys);
+        return show(config('status.success'), $result);
+    }
+}

+ 29 - 0
app/common/lib/Arr.php

@@ -0,0 +1,29 @@
+<?php
+
+namespace app\common\lib;
+
+
+class Arr
+{
+    /**
+     * 分类树,支持无限极分类
+     * @param $data
+     * @return array
+     */
+    public static function getTree($data): array
+    {
+        $items = [];
+        foreach ($data as $v) {
+            $items[$v['id']] = $v;
+        }
+        $tree = [];
+        foreach ($items as $id => $item) {
+            if (isset($items[$item['pid']])) {
+                $items[$item['pid']]['list'][] = &$items[$id];
+            } else {
+                $tree[] = &$items[$id];
+            }
+        }
+        return $tree;
+    }
+}

+ 9 - 16
app/common/model/mysql/Category.php

@@ -28,7 +28,15 @@ class Category extends Model
             'status' => config('status.mysql.table_normal')
         ];
 
-        return $this->where($where)->field($field)->select();
+        $order = [
+            'listorder' => 'desc',
+            'id' => 'desc',
+        ];
+
+        return $this->where($where)
+            ->field($field)
+            ->order($order)
+            ->select();
     }
 
     /**
@@ -61,19 +69,4 @@ class Category extends Model
         $data['update_time'] = time();
         return $this->where(['id' => $id])->save($data);
     }
-
-    /**
-     * 根据pid获取子分类的个数
-     * @param $condition
-     * @return mixed
-     */
-    public function getChildCountInPids($condition)
-    {
-        $where[] = ['pid', 'in', $condition['pid']];
-        $where[] = ['status', '<>', config('status.mysql.table_delete')];
-        return $this->where($where)
-            ->field(['pid', 'count(*) as count'])
-            ->group('pid')
-            ->select();
-    }
 }