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

标签 mysql ruby-on-rails-3 rubygems

我有一个如下表

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/

相关文章:

mysql - NOT EXISTS 条件下的查询速度问题

php - 基于 MySQL 结果在 PHP while 循环内每第一次和第四次运行脚本

postgresql - 从 Macports 切换到 Homebrew 后,Rails 和 Postgres 相处得并不好; PG错误: ERROR: unrecognized time zone name: "UTC"

ruby-on-rails - 命名空间嵌套资源

mysql - 用户表 - 一张或两张表?

如果使用 ORDER BY 字符串列,MySQL 查询需要很长时间才能执行

ruby-on-rails - Rails 无法识别从 Ruby 脚本发布的参数

ruby - "bourbon"的导入在 Je​​kyll 设置中不起作用

ruby-on-rails - bundle install --without production 有什么作用?

ruby-on-rails - 如何处理依赖于配置的 gem 依赖项?