diff --git a/app/api/controller/Region.php b/app/api/controller/Region.php index 88d1d438..2ea0c90a 100644 --- a/app/api/controller/Region.php +++ b/app/api/controller/Region.php @@ -44,7 +44,9 @@ class Region extends Controller */ public function tree(): Json { - $list = RegionModel::getCacheTree(); + $model = new RegionModel(); + $list = $model->getNewTreeList(); + //$list = array_values($list); return $this->renderSuccess(compact('list')); } } diff --git a/app/common/model/Region.php b/app/common/model/Region.php index 5aec6496..4e9d4f6b 100644 --- a/app/common/model/Region.php +++ b/app/common/model/Region.php @@ -139,7 +139,46 @@ class Region extends BaseModel } return $cacheData[$item]; } - + public function getNewTreeList(){ + $treeList = Cache::get('region2'); + if ($treeList) { + return $treeList; + } + $allList = self::withoutGlobalScope() + ->field('id, pid, name, level') + ->select() + ->toArray(); + + $treeList = []; + $i = 0; + foreach ($allList as $pKey => $province) { + if ($province['level'] == 1) { // 省份 + $treeList[$i] = $province; + unset($allList[$pKey]); + $j = 0; + foreach ($allList as $cKey => $city) { + + if ($city['level'] == 2 && $city['pid'] == $province['id']) { // 城市 + $treeList[$i]['children'][$j] = $city; + unset($allList[$cKey]); + $m = 0; + foreach ($allList as $rKey => $region) { + if ($region['level'] == 3 && $region['pid'] == $city['id']) { // 地区 + $treeList[$i]['children'][$j]['children'][$m] = $region; + unset($allList[$rKey]); + $m++; + } + } + $j++; + } + } + $i++; + } + } + Cache::tag('cache')->set('region2', $treeList); + return $treeList; + + } /** * 获取地区缓存 * @return array