我一直在试验 PostgreSQL 的 Ltree 扩展。我想用它来存储分层的待办事项列表数据(即带有子列表的列表)。它工作得很好,但是在花费了相当长的时间之后,我仍然找不到从数据库中以分层 JSON 格式检索信息的好方法。这是我想要实现的示例:
id | content | position | parent_id | parent_path
----+------------------------+-----------+----------+-------------+
1 | Fix lecture notes. | 1 | | root
2 | Sort out red folder. | 1 | 1 | root.1
3 | Order files. | 1 | 2 | root.1.2
4 | Label topics. | 2 | 2 | root.1.2
5 | Sort out blue folder. | 2 | 1 | root.1
6 | Look for jobs. | 2 | | root
从这里,到下面的 json 输出:
[
{
"id":1,
"content":"Fix lecture notes.",
"position":1,
"parent_id":null,
"parent_path":"root",
"children":[
{
"id":2,
"content":"Sort out red folder.",
"position":1,
"parent_id":1,
"parent_path":"root.1",
"children":[
{
"id":3,
"content":"Order files.",
"position":1,
"parent_id":2,
"parent_path":"root.1.2",
"children":[]
},
{
"id":4,
"content":"Label topics.",
"position":2,
"parent_id":2,
"parent_path":"root.1.2",
"children":[]
}
]
},
{
"id":2,
"content":"Sort out blue folder.",
"position":2,
"parent_id":1,
"parent_path":"root.1",
"children":[]
}
]
},
{
"id":1,
"content":"Look for jobs.",
"position":1,
"parent_id":null,
"parent_path":"root",
"children":[]
}
]
有没有什么巧妙的方法可以做到这一点,也许是 Python 服务器端?真的在寻找想法!