Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all children of children and so on

I am using MongoDb as database.

I want all the children of children and so on. Lets Suppose

  • A has B & C children
  • B has D & E children
  • D has F & G children

So when I query for children node A. I get all the children as output such as B C D E F G

 C = Customer.find_by(:id => "SOME_ID")
 C.children #list all children upto one level

So can anyone suggest me the way, to get recursive children.

Customer model

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

Can anybody please help me out. Or suggest a way to accomplish this.

like image 672
compsy Avatar asked Jul 16 '18 20:07

compsy


1 Answers

You can add a custom method to gather all the children of a customer, and children of children, and so on.

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
like image 191
Jagdeep Singh Avatar answered Sep 27 '22 22:09

Jagdeep Singh