我正在使用MongoDb作为数据库。
我要所有孩子的孩子等等。 假设
因此,当我查询子节点 A 时。我得到所有孩子作为输出,例如B C D E F G
C = Customer.find_by(:id => "SOME_ID")
C.children #list all children upto one level
所以任何人都可以给我建议的方式,让孩子递归。
客户模型
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
有人可以帮助我吗?或提出一种实现此目的的方法。
答案 0 :(得分:4)
您可以添加自定义方法来收集客户的所有子代以及子代的子代,等等。
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