class Store {
Integer storeNumber
//List employees
//List managers
static hasMany = [employees:Person,
managers:Person]
static constraints = {
employees(nullable:true)
managers(nullable:true)
}
}
class Person {
String name
String roll
static belongsTo = [store:Store]
static constraints = {
role inList: ['employee','manager']
}
}
现在添加一个商店
Store store = new Store(storeNumber: 1).save()
if (store) {
Person person = new Person(name:'fred', roll:'employee', store:store).save()
if (person) {
store.addToEmployees(person)
}
}
因此,头痛的收获显然是反向查找父级的快速方法,替代方法是下面描述的松散关系,它不关心父级,所以你不需要最后一点,显然会松散依赖问题你打到现在
结束 E2A
你需要一个有另一个关系
或者,如果您不关心 belongsTo 关系,那么事情会更容易
static belongsTo = Store
那么这个因素就不再是问题了。
不同之处在于您拥有的当前方法与我向您展示的后者 - 如果查询是从孩子开始的,您可以轻松地从孩子反向走回父母
无论哪种方式,您始终可以从父项开始查询,然后加入子项并查找子项
先生,你适合什么?
最终编辑
您知道,当您多年来一直在做这些事情时,您会发现以其他方式做事的方法:
假设您确实设置了从 Parent 到 Child 的松散/弱引用,并且您想要访问 Parent。方法如下:
Class User {
String username
static hasMany=[childs:Children]
}
Class Children {
String firstName
static belongsTo=User
// now to get access back to parent user without knowing parent a hackish thing like this can be done:
User getUser() {
User.findByChilds(this)
}
String getUserName() {
return user?.username
}
}
现在你可以从一个孩子做 ${instance.user} 或 ${instance.userName} 这将绑定回父对象并通过子对象本身找到findByChilds(this) 几年前我猜这会扭曲我