我正在使用名为 ltree_hierarchy( https://github.com/cfabianski/ltree_hierarchy) 的 rails 和 gem 使用分层数据模型。因为每个节点都有一个父 ID(它是当前节点的直接父节点)。
1
2 3
4 5 6 7
层次结构是使用 postgres 的 ltree 扩展实现的。在 gem ltree_hierarchy 中,将保存父级和路径。
node parent path
1 NULL 1
2 1 1.2
3 1 1.3
4 2 1.2.4
5 2 1.2.5
6 3 1.3.6
7 3 1.3.7
我可以使用节点的 parent_id 获取兄弟节点、父节点和子节点。类似的东西,
select * from table where parent_id = 1; # for getting the children of a node 1
select * from table where parent_id = 1 and id !=2; # for getting the sibling of a node 2
是否有任何建议可以在单个查询中获取节点的子节点和孙节点?
最佳答案
因为你在下面使用 postgres 的 LTREE
- 你可以直接查询它(见 postgres documentation )就像
select * from table where path ~ '1234.*{1,2}'
(这里的1234
是parent的id,*{1,2}
表示最少匹配一级,最多匹配2级)
关于ruby-on-rails - 让 child 、孙子进入层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54850228/