gpt4 book ai didi

mysql - 需要在轨道上排列自己、 child 和 child 的 child

转载 作者:行者123 更新时间:2023-11-29 08:41:50 26 4
gpt4 key购买 nike

我有一个如下表

Mysql table with parent ids

好吧,在这个表中每个用户都有一个父用户,那么如果我们选择一个用户,那么它的 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->childrendsparent->parents,只需迭代调用函数上级或下级 strong> 直到得到 nil 或 [] 数组。

关于mysql - 需要在轨道上排列自己、 child 和 child 的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13580101/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com