【问题标题】:Get all children of children and so on获取孩子的所有孩子等等
【发布时间】:2018-07-16 20:35:55
【问题描述】:

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

我想要孩子的所有孩子等等。 让我们假设

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

所以当我查询子节点 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

谁能帮帮我。或者建议一种方法来实现这一点。

【问题讨论】:

    标签: ruby-on-rails ruby mongodb ruby-on-rails-3 mongoid


    【解决方案1】:

    您可以添加自定义方法来收集客户的所有孩子,以及孩子的孩子等等。

    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
    

    【讨论】:

    • 谢谢你,你是生命的救星。你能解释一下你的代码实际上在做什么吗?对我帮助很大
    • 它遍历cust.children,然后递归调用descendents,返回它们的孩子,然后调用descendents,以此类推。
    • 你能帮我修改一下上面的函数来找出第​​N级的孩子吗?不是所有的孩子,把孩子带到第 N 级。当我试图将参数传递给这个方法时。但我未能在地图中使用参数并递归调用它
    • 这可能需要一些时间。您为什么不自己尝试,如果仍然无法弄清楚,请单独提出一个问题,以便其他人可以提供帮助?
    • 是的,当然。谢谢
    猜你喜欢
    • 2012-03-07
    • 2018-01-29
    • 2014-03-27
    • 1970-01-01
    • 2021-08-19
    • 2013-09-27
    • 1970-01-01
    • 2015-05-16
    • 2016-11-30
    相关资源
    最近更新 更多