GRAILS:找到一个自我引用的一个一对多的关系,所有的孩子(GRAILS: Find all ch

2019-06-27 14:54发布

Grails中,

如何将一个找到一个一对多的关系,例如,所有的孩子,

class Employee {
    static hasMany = [ subordinates: Employee ]
    static belongsTo = [ manager: Employee ]
}

使用单经理,如何将一个获得所有下属的下属(如穿越对象图)?

Answer 1:

如果你不希望修改域名递归关闭工作。 否则,你可能会短暂属性添加到Employee域类像allSubordinates在这个例子:

class Employee {
    String name
    static hasMany = [ subordinates: Employee ]
    static belongsTo = [ manager: Employee ]
    static transients = ['allSubordinates']
    def getAllSubordinates() {
        return subordinates ? subordinates*.allSubordinates.flatten() + subordinates : []
    }
}

这是一个集成测试,看看它在行动:

import grails.test.*

class EmployeeTests extends GrailsUnitTestCase {
    Employee ceo
    Employee middleManager1, middleManager2
    Employee e1, e2, e3, e4, e5, e6

    protected void setUp() {
        super.setUp()
        ceo = new Employee(name:"CEO")
            middleManager1 = new Employee(name:"Middle Manager 1")
                e1 = new Employee(name:"e1")
                e2 = new Employee(name:"e2")
                e3 = new Employee(name:"e3")
            middleManager2 = new Employee(name:"Middle Manager 2")
                e4 = new Employee(name:"e4")
                e5 = new Employee(name:"e5")
                e6 = new Employee(name:"e6")

        ceo.subordinates = [middleManager1, middleManager2]
        middleManager1.subordinates = [e1,e2,e3]
        middleManager2.subordinates = [e4,e5,e6]
        assert ceo.save()
    }

    void testAllSubordinates() {
        def topLevelManager = Employee.get(ceo.id)
        assertNotNull(topLevelManager);
        assertEquals(8, topLevelManager.allSubordinates?.size())
    }
}


Answer 2:

 //Make a recursive closure
 def printAll

 printAll = { emp ->
    subordinates.each { 
                        println it
                        printAll emp
                      }
 }


文章来源: GRAILS: Find all children in a self-referenced one-to-many relationship