[英]How to get the descendants of all objects in an array? (Rails + ancestry gem)
I am using this gem https://github.com/stefankroes/ancestry for my People modle. 我正在使用这个宝石https://github.com/stefankroes/ancestry为我的人物模型。 The table looks like this:
该表如下所示:
+----+----------+
| id | ancestry |
+----+----------+
| 1 | NULL |
| 2 | 1 |
| 3 | 1 |
| 4 | 1/2 |
| 5 | 1/3 |
| 6 | NULL |
| 7 | 1/2 |
| 8 | 1/2 |
| 9 | 1/3 |
| 10 | NULL |
| 11 | 10 |
| 12 | 10 |
| 13 | NULL |
| 14 | NULL |
| 15 | 6 |
| 16 | 6 |
| 17 | 6/16 |
| 18 | 6 |
| 19 | 6/18 |
| 20 | 14 |
+----+----------+
What I want to query is: 我想要查询的是:
given two people with id 1 and 6 给两个身份1和6的人
get all descendants of these two people 得到这两个人的所有后代
in one query instead of querying one by one since I need to put this into an Arel.or method. 在一个查询中而不是逐个查询,因为我需要将它放入Arel.or方法中。
I knew that using: 我知道使用:
People.select("id").where(People.arel_table[:ancestry].matches("6/%"))
generates LIKE sql statement and returns all grandchildren of the people with id 6. I also knew: 生成LIKE sql语句并返回id为6的人的所有孙子。我也知道:
People.select("id").where(People.arel_table[:ancestry].matches(["1/%","6/%"]))
doesn't work because it generates invalid LIKE statement: 不起作用,因为它生成无效的LIKE语句:
SELECT id FROM `people` WHERE (`people`.`ancestry` LIKE '1/%', '6/%')
On the other hand, I knew: 另一方面,我知道:
People.select("id").where(People.arel_table[:ancestry].in(["1", "6"]))
generates IN sql statement and returns all children (but not grandchildren) of both 1 and 6. I also knew: 生成IN sql语句并返回1和6的所有子项(但不是孙子项)。我也知道:
People.select("id").where(People.arel_table[:ancestry].in(["1/%", "6/%"]))
returns nothing because IN statement works as precisely matching. 什么都不返回,因为IN语句作为精确匹配。
My question then is: how can I put them all into a (probably chaining) query to get all descendants of both 1 and 6? 我的问题是:如何将它们全部放入(可能是链接的)查询中以获得1和6的所有后代? In this example, I would expect the result is: [ 2, 3, 4, 5, 7, 9, 15, 16, 17, 18, 19 ].
在这个例子中,我希望结果是:[2,3,4,5,7,9,15,16,17,18,19]。
Thank you very much for the suggestions 非常感谢您的建议
People.select("id").where(People.arel_table[:ancestry].matches("1/%").or(People.arel_table[:ancestry].matches("6/%"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.