Grails中,
如何将一个找到一个一对多的关系,例如,所有的孩子,
class Employee {
static hasMany = [ subordinates: Employee ]
static belongsTo = [ manager: Employee ]
}
使用单经理,如何将一个获得所有下属的下属(如穿越对象图)?
Grails中,
如何将一个找到一个一对多的关系,例如,所有的孩子,
class Employee {
static hasMany = [ subordinates: Employee ]
static belongsTo = [ manager: Employee ]
}
使用单经理,如何将一个获得所有下属的下属(如穿越对象图)?
如果你不希望修改域名递归关闭工作。 否则,你可能会短暂属性添加到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())
}
}
//Make a recursive closure
def printAll
printAll = { emp ->
subordinates.each {
println it
printAll emp
}
}