[英]How to create hierarchal json object using ltree query results? (postgresql)
我正在嘗試使用 postgres 為自定義類別創建一個存儲系統。
在四處尋找潛在的解決方案后,我決定嘗試使用ltree ;
以下是原始數據的示例;
+----+---------+---------------------------------+-----------+
| id | user_id | path | name |
+----+---------+---------------------------------+-----------+
| 1 | 1 | root.test | test |
| 2 | 1 | root.test.inbox | inbox |
| 3 | 1 | root.personal | personal |
| 4 | 1 | root.project | project |
| 5 | 1 | root.project.idea | idea |
| 6 | 1 | root.personal.events | events |
| 7 | 1 | root.personal.events.janaury | january |
| 8 | 1 | root.project.objective | objective |
| 9 | 1 | root.personal.events.february | february |
| 10 | 1 | root.project.objective.january | january |
| 11 | 1 | root.project.objective.february | february |
+----+---------+---------------------------------+-----------+
我認為首先對結果進行排序並從路徑返回中刪除頂層可能會更容易。 使用;
select id, name, subpath(path, 1) as path, nlevel(subpath(path, 1)) as level from testLtree order by level, path
我明白了;
+----+-----------+----------------------------+-------+
| id | name | path | level |
+----+-----------+----------------------------+-------+
| 3 | personal | personal | 1 |
| 4 | project | project | 1 |
| 1 | test | test | 1 |
| 6 | events | personal.events | 2 |
| 5 | idea | project.idea | 2 |
| 8 | objective | project.objective | 2 |
| 2 | inbox | test.inbox | 2 |
| 9 | february | personal.events.february | 3 |
| 7 | january | personal.events.january | 3 |
| 11 | february | project.objective.february | 3 |
| 10 | january | project.objective.january | 3 |
+----+-----------+----------------------------+-------+
我希望能夠以某種方式將這個結果轉換為一組 JSON 數據。 我想要一個與此類似的輸出;
personal: {
id: 3,
name: 'personal',
children: {
events: {
id: 6,
name: 'events',
children: {
january: {
id: 7,
name: 'january',
children: null
},
february: {
id: 9,
name: 'february',
children: null
}
}
}
}
},
project: {
id: 4,
name: 'project',
children: {
idea: {
id: 5,
name: 'idea',
children: null
},
objective: {
id: 8,
name: 'objective',
children: {
january: {
id: 10,
name: 'january',
children: null
},
february: {
id: 11,
name: 'february',
children: null
}
}
}
}]
},
test: {
id: 1,
name: 'test',
children: {
inbox: {
id: 2,
name: 'inbox',
children: null
}
}
}
我一直在尋找最好的方法來做到這一點,但沒有遇到任何對我有意義的解決方案。 但是,由於我是 postgres 和 SQL 的新手,一般來說這是意料之中的。
我想我可能不得不使用遞歸查詢? 我對什么是最好的方法/執行感到有些困惑。 非常感謝任何幫助/建議! 和任何進一步的問題,請詢問。
我已經把所有東西都放到了下面的 sqlfiddle 中;
我遇到了和你一樣的問題。 我在 PostgreSQL 中遇到了很大的困難,解決起來變得過於復雜。 由於我使用的是 Django(Python 框架),所以我決定使用 Python 來解決它。 如果它可以幫助我遇到相同情況的任何人,我想分享代碼: https : //gist.github.com/eherrerosj/4685e3dc843e94f3ef8645d31dbe490c
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.