Grails域自引用递归调用

Grails域自引用递归调用,grails,recursion,groovy,gorm,Grails,Recursion,Groovy,Gorm,这是我的域类: class Category { String name static hasMany = [subCategories: Category] static belongsTo = [parentCategory: Category] static mapping = { subCategories joinTable: false, column: "parent_id" } static constrain

这是我的域类:

class Category {
    String name

    static hasMany = [subCategories: Category]
    static belongsTo = [parentCategory: Category]

    static mapping = {
        subCategories joinTable: false, column: "parent_id"
    }

    static constraints = {
        parentCategory nullable: true
    }}
Category是一个域类,具有对父类和子类列表的自引用

现在我想要这样的东西:给定一个父类别id,我想要一个属于该id的所有子类别的列表。(注意:不是直接子类别,id下的所有子类别)

例如,id 1有子项2和3,id 2有子项4和5

假设我从客户那里得到了类别id 1,我想要一个id为2,3,4,5的子类别


利用Groovy,实现这一点的最佳代码是什么?

未经测试的代码,但可能会让您朝着正确的方向前进。也许有一种“更常规”的方法可以做到这一点,但我不确定

def findAllChildren(category, results = []) {
   category.subCategories.each { child ->
      results << child
      findAllChildren(child, results)
   }
}

def someOtherMethod() {
  def allChildren = []
  findAllChildren(parentCategory, allChildren)
}
def findAllChildren(类别,结果=[]){
category.subCategories.each{child->

结果您必须使用自连接hql查询,而不是使用每个查询,因为它会增加响应时间,这对您的应用程序不利。