【发布时间】:2019-02-25 02:12:57
【问题描述】:
我正在使用名为 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
有什么建议可以在单个查询中获取节点的子节点和大子节点吗?
【问题讨论】:
-
您为什么要这样做?只需使用图书馆来获取孩子和他们的孙子。
-
我查过了。但是没有办法得到孙子。我想要的是在子树的某个深度获得一个节点。我提到的是获取节点的子节点和孙节点,它基本上是任何节点的 2 级。
-
就在文档中:
root.children.first.children.first # => subchild -
我可以使用您指定的方法获得所需节点的任何子节点的孙子节点。但我不能得到所有孩子的孩子。无论如何感谢您的回复。
-
first只是列表中第一个元素的简写。也许descendants也有用
标签: ruby-on-rails postgresql hierarchical-data ltree