0

私は次のようなテーブルを持っています

親IDを持つMysqlテーブル

この表では、すべてのユーザーに親ユーザーがいます。ユーザーを選択すると、そのID、子ID、子子IDが配列として返されます。gemを使用せずにレールでこの値を取得するには、クエリが必要です。あなたの助けに感謝します:->

4

2 に答える 2

1

あなたはSQLアンチパターンに取り残されています。そのように構築されたツリーで操作を実行することは非常に非効率的です。そのためにgemを使用する必要があるとは言いませんが、このデータを保持するためのよりスマートな方法を使用することを検討してください(検索するとsql tree structure意味のある結果が得られるはずです)。

探しているクエリには、2つの自己結合が必要です。

SELECT t1.id user_ids, t2.id children_ids, t3.id children_children_ids FROM users t1 
  LEFT JOIN users t2 ON t2.parent = t1.id
  LEFT JOIN users t3 ON t3.parent = t2.id

一方、Railsモデルで自己関係が定義されている場合は、次のように簡単に記述できます。

user.children #=> (array of children)
user.children.flat_map(&:children) #=> (array of grandchildren)

この関係の定義は次のようになります。

class User << ActiveRecord::Base
  has_many :children, class_name: User, foreign_key: 'parent'
end
于 2012-11-27T08:36:43.697 に答える
1
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

上司(親)または部下(子)のいずれかを呼び出すと、必要な結果が得られます
。例:- [2,4,6,8] 子->子または親- >親のいずれ
かを取得する場合は、呼び出し関数を繰り返し実行します。nilまたは[]配列を取得するまで上位または下位。

于 2012-11-27T11:59:43.743 に答える