使用递归实现地址数据菜单
跟网上的不同的是,我这种方式是以时间换空间的做法,不会一次性把数据全查出来再慢慢遍历,而是每次查询是否存在子级,有就递归下去查。
数据量大时,查库的次数比较多,数据量少时对数据库查询次数少,压力较小,但是多次查询不会出现一次查询数据量很大卡住的情况。
思路
- 先获取一级菜单,对每个一级菜单设子区域。
- 如果子区域还有子区域,就递归查询,直到查不到子区域返回。
- 递归的核心就是在方法中设置一个返回条件,防止无限递归下去。
1 | * liukai |
1 |
|
结果
1 | [{"fullLabel":"北京市","id":2,"label":"北京市","parentId":0,"regionBeanList":[],"sortId":1},{"fullLabel":"天津市","id":22,"label":"天津市","parentId":0,"regionBeanList":[],"sortId":2},{"fullLabel":"上海市","id":783,"label":"上海市","parentId":0,"regionBeanList":[],"sortId":3},{"fullLabel":"辽宁省","id":457,"label":"辽宁省","parentId":0,"regionBeanList":[{"fullLabel":"辽宁省-沈阳市","id":458,"label":"沈阳市","parentId":457,"regionBeanList":[],"sortId":1},{"fullLabel":"辽宁省-铁岭市","id":472,"label":"铁岭市","parentId":457,"regionBeanList":[],"sortId":2},{"fullLabel":"辽宁省-大连市","id":480,"label":"大连市","parentId":457,"regionBeanList":[],"sortId":3},{"fullLabel":"辽宁省-鞍山市","id":491,"label":"鞍山市","parentId":457,"regionBeanList":[],"sortId":4},{"fullLabel":"辽宁省-抚顺市","id":499,"label":"抚顺市","parentId":457,"regionBeanList":[],"sortId":5},{"fullLabel":"辽宁省-本溪市","id":507,"label":"本溪市","parentId":457,"regionBeanList":[],"sortId":6},{"fullLabel":"辽宁省-丹东市","id":514,"label":"丹东市","parentId":457,"regionBeanList":[],"sortId":7},{"fullLabel":"辽宁省-锦州市","id":521,"label":"锦州市","parentId":457,"regionBeanList":[],"sortId":8},{"fullLabel":"辽宁省-营口市","id":529,"label":"营口市","parentId":457,"regionBeanList":[],"sortId":9},{"fullLabel":"辽宁省-阜新市","id":536,"label":"阜新市","parentId":457,"regionBeanList":[],"sortId":10},{"fullLabel":"辽宁省-辽阳市","id":544,"label":"辽阳市","parentId":457,"regionBeanList":[],"sortId":11},{"fullLabel":"辽宁省-朝阳市","id":552,"label":"朝阳市","parentId":457,"regionBeanList":[],"sortId":12},{"fullLabel":"辽宁省-盘锦市","id":560,"label":"盘锦市","parentId":457,"regionBeanList":[{"fullLabel":"辽宁省-三级数据","id":561,"label":"三级数据","parentId":560,"regionBeanList":[],"sortId":13},{"fullLabel":"辽宁省-三级数据","id":562,"label":"三级数据","parentId":560,"regionBeanList":[],"sortId":13},{"fullLabel":"辽宁省-三级数据","id":563,"label":"三级数据","parentId":560,"regionBeanList":[],"sortId":13},{"fullLabel":"辽宁省-三级数据","id":564,"label":"三级数据","parentId":560,"regionBeanList":[],"sortId":13},{"fullLabel":"辽宁省-三级数据","id":565,"label":"三级数据","parentId":560,"regionBeanList":[],"sortId":13},{"fullLabel":"辽宁省-三级数据","id":566,"label":"三级数据","parentId":560,"regionBeanList":[{"fullLabel":"辽宁省-四级数据","id":666,"label":"四级数据","parentId":566,"regionBeanList":[],"sortId":13}],"sortId":13}],"sortId":13}],"sortId":8}] |
我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=1n712ep0u8906
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 人话翻译机!
评论