我有一个如下表
好吧,在这个表中每个用户都有一个父用户,那么如果我们选择一个用户,那么它的 id 、子代 id 和子代子代 id 应该作为数组返回。我需要一个查询来获取 Rails 中的这些值,而不使用任何 gem 。感谢您的帮助:->
最佳答案
class User << ActiveRecord::Base
def self.build_tree(reverse=false)
g = Array.new
self.find(:all).each do |p|
if reverse
g << [p.id,p.parent]
else
g << [p.parent,p.id]
end
end
g
end
def self.subordinates(man_id)
g = self.build_tree false
g.map{|i| i[1] if i[0]==man_id.to_i}.compact
end
def self.superiors(user_id)
g = self.build_tree true
g.map{|i| i[1] if i[0]==user_id.to_i}.compact
end
end
当调用上级( parent )或下属(子女)时,它将给出所需的结果
例如:- [2,4,6,8]
如果您想获得children->childrends或parent->parents,只需迭代调用函数上级或下级 strong> 直到得到 nil 或 [] 数组。
关于mysql - 需要在轨道上排列自己、 child 和 child 的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13580101/