我在使用 Grails 建立多对多关系时遇到了一些问题。以下是否有明显错误:
class Person {
static hasMany = [friends: Person]
static mappedBy = [friends: 'friends']
String name
List friends = []
String toString() {
return this.name
}
}
class BootStrap {
def init = { servletContext ->
Person bob = new Person(name: 'bob').save()
Person jaq = new Person(name: 'jaq').save()
jaq.friends << bob
println "Bob's friends: ${bob.friends}"
println "Jaq's friends: ${jaq.friends}"
}
}
我希望 Bob 与 Jaq 成为 friend ,反之亦然,但我在启动时得到以下输出:
Running Grails application..
Bob's friends: []
Jaq's friends: [Bob]
(我正在使用 Grails 1.2.0)
最佳答案
这似乎可行:
class Person {
static hasMany = [ friends: Person ]
static mappedBy = [ friends: 'friends' ]
String name
String toString() {
name
}
}
然后在 BootStrap 中:
class BootStrap {
def init = { servletContext ->
Person bob = new Person(name: 'bob').save()
Person jaq = new Person(name: 'jaq').save()
jaq.addToFriends( bob )
println "Bob's friends: ${bob.friends}"
println "Jaq's friends: ${jaq.friends}"
}
}
我得到以下信息:
Running Grails application..
Bob's friends: [jaq]
Jaq's friends: [bob]
关于grails - 在Grails域对象中维护自引用多对多关系的双方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2517390/