获取所有孩子的孩子,依此类推

com*_*psy 3 ruby ruby-on-rails mongodb mongoid ruby-on-rails-3

我正在使用MongoDb作为数据库。

我要所有孩子的孩子等等。假设

  • A有B&C孩子
  • B有D&E孩子
  • D有F&G孩子

因此,当我查询子节点A时。我得到所有孩子作为输出,例如BCDEFG

 C = Customer.find_by(:id => "SOME_ID")
 C.children #list all children upto one level
Run Code Online (Sandbox Code Playgroud)

因此,谁能给我建议的方式,让孩子递归。

客户模型

class Customer

  include Mongoid::Document
  field :email, type: String
  field :referral_id, type: String
  belongs_to :parent, class_name: 'Customer',foreign_key: "referral_id", optional: true
  has_many :children, :class_name => 'Customer', :foreign_key => "referral_id"

end
Run Code Online (Sandbox Code Playgroud)

有人可以帮我吗。或建议一种方法来完成此任务。

Jag*_*ngh 5

您可以添加自定义方法来收集客户的所有子代以及子代的子代,依此类推。

class Customer
  def descendants
    self.children | self.children.map(&:descendants).flatten
  end
end

cust = Customer.find(<id>)
cust.descendants
 => # Array of all the descendants of customer
Run Code Online (Sandbox Code Playgroud)