作者:桑正青0V1 | 来源:互联网 | 2022-12-10 14:42
我正在使用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
因此,谁能给我建议的方式,让孩子递归。
客户模型
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
有人可以帮我吗。或建议一种方法来完成此任务。
1> Jagdeep Sing..:
您可以添加自定义方法来收集客户的所有子代以及子代的子代,依此类推。
class Customer
def descendants
self.children | self.children.map(&:descendants).flatten
end
end
cust = Customer.find()
cust.descendants
=> # Array of all the descendants of customer