层级分类怎么根据指定分类获取到,分类的父级和它的子级分类?

数据库如下字段:

cat_id    cat_name        parent_id   grade

4094 分类1 0 1

4095 分类2 4094 2

4096 分类3 4095 3

4097 分类4 4096 4

4099 分类测试 4096 4

4100 分类测试 0 1

怎么根据指定的分类获取到它的父级分类和子级分类生成如下格式:
比如传入的id为 2777

{

"cat_id":"2776",

"cat_name":"办公耗材",

"goods_num":"0",

"sort_order":"2",

"grade":"1",

"cat_attr":"0",

"children":[

{

"cat_id":"2777",//分类id

"cat_name":"针式\/票据打印机色带",//分类名称

"goods_num":"0",

"sort_order":"50",

"grade":"2",

"parent_id":"2776",

"cat_attr":"0",

"is_son":false,//是否有子级数据

"children":[

{

"cat_id":"2778",

"cat_name":"色带架",

"goods_num":"0",

"sort_order":"50",

"grade":"3",

"cat_attr":"14",

"is_son":true,

"children":[

]

},

{

"cat_id":"2779",

"cat_name":"色带芯",

"goods_num":"0",

"sort_order":"50",

"grade":"3",

"cat_attr":"10",

"is_son":true,

"children":[

]

},

{

"cat_id":"2780",

"cat_name":"标签机色带",

"goods_num":"0",

"sort_order":"50",

"grade":"3",

"cat_attr":"12",

"is_son":true,

"children":[

]

},

{

"cat_id":"2781",

"cat_name":"针式票据打印机色带",

"goods_num":"0",

"sort_order":"50",

"grade":"3",

"cat_attr":"11",

"is_son":true,

"children":[

]

},

{

"cat_id":"2782",

"cat_name":"证卡打印机\/POS机色带",

"goods_num":"0",

"sort_order":"50",

"grade":"3",

"cat_attr":"10",

"is_son":true,

"children":[

]

},

{

"cat_id":"2783",

"cat_name":"碳带",

"goods_num":"0",

"sort_order":"50",

"grade":"3",

"cat_attr":"10",

"is_son":true,

"children":[

]

}

]

}

]

}


回答:

你这样例返回 父子级关系的字段没有。 不好理解。加个parent_id。才好理解你要的什么结构:是单链树。还是节点的全量子树


回答:

增加一列path以,分割的所有分类节点

cat_idcat_nameparent_idgradepath
4094分类1014094
4095分类2409424094,4095
4096分类3409534094,4095,4096
4097分类4409644094,4095,4096,4097
4099分类测试409644094,4095,4096,4097,4099
4100分类测试014094,4095,4096,4097,4099,4100

当取出任意节点时,根据path可立刻取出层级、指定上级和下级的所有分类

以上是 层级分类怎么根据指定分类获取到,分类的父级和它的子级分类? 的全部内容, 来源链接: utcz.com/p/944903.html

回到顶部