[英]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.