Search code examples
grailsrecursiongroovygrails-orm

Grails domain self-reference recursive call


Here is my domain class:

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 is a domain class and has self-reference to both parent and list of children.

Now I want something like this: given a parent category id, I want a list of all sub-categories belong to this id. (NB: not direct children, all the children under the id)

For example, id 1 has children 2 and 3, and 2 has children 4 and 5.

Given I got category id 1 from client, I want a sub categories with id 2,3,4,5

Taken advantage of Groovy, what is the best code to implement that?


Solution

  • Untested code but might get you moving in the right direction. There might be a "groovier" way to do this, but I'm not sure.

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