Объединить результаты по рекурсивному запросу с категориями - PullRequest
0 голосов
/ 09 апреля 2019

У меня есть базовая CATEGORIES -подобная таблица, состоящая из полей, таких как 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":[

      ]
   }
]
...