我有一个基本的类别表格,由诸如primary_key,parent_id,title等字段组成。
我能够使用CTE检索结果并将其转换为json数组,但我想按父级分组来获取它们。我的查询现在为同一父级返回一个新的json数组。
为简单起见,我只包括一名主要父母,但其中许多是顶级父母。
到目前为止:
with recursive parents as
(
select n.feature_id, n.title, '{}'::int[] as parents, 0 as level
from features n
where n.parent_id is null
union all
select n.feature_id, n.title, parents || n.parent_id, level+1
from parents p
join features n on n.parent_id = p.feature_id
where not n.feature_id = any(parents)
),
children as
(
select n.parent_id,
json_agg(jsonb_build_object(
'feature_id', n.feature_id,
'title', n.title,
'slug', n.slug
))::jsonb as js
from parents tree
join features n using(feature_id)
where level = 2 and not feature_id = any(parents)
group by n.parent_id
union all
select n.parent_id, jsonb_build_object('category', n.title) || jsonb_build_object('subcategories', js) as js
from children tree
join features n on n.feature_id = tree.parent_id
)
select jsonb_agg(js) as features
from children
where parent_id is null
当前结果集:
[
{
"category":"Room Details",
"subcategories":{
"category":"Appliances",
"subcategories":[
{
"slug":"dishwasher",
"title":"Dishwasher",
"feature_id":39
},
{
"slug":"dryer",
"title":"Dryer",
"feature_id":40
}
]
}
},
{
"category":"Room Details",
"subcategories":{
"category":"Indoor Features",
"subcategories":[
{
"slug":"attic",
"title":"Attic",
"feature_id":33
},
{
"slug":"cable-ready",
"title":"Cable ready",
"feature_id":34
}
]
}
}
]
我要实现的目标:
[
{
"category":"Room Details",
"subcategories":[
{
"category":"Appliances",
"subcategories":[
{
"slug":"dishwasher",
"title":"Dishwasher",
"feature_id":39
},
{
"slug":"dryer",
"title":"Dryer",
"feature_id":40
}
]
},
{
"category":"Indoor Features",
"subcategories":[
{
"slug":"attic",
"title":"Attic",
"feature_id":33
},
{
"slug":"cable-ready",
"title":"Cable ready",
"feature_id":34
}
]
}
]
},
{
"category":"Building Details",
"subcategories":[
]
},
{
"category":"Utility Details",
"subcategories":[
]
}
]