给定以下用户类:
class User {
String name
static hasMany = [friends: User]
}
我希望一个用户可以有很多朋友,它们是用户域类的实例。
如何实现用户的好友关系?
给定以下用户类:
class User {
String name
static hasMany = [friends: User]
}
我希望一个用户可以有很多朋友,它们是用户域类的实例。
如何实现用户的好友关系?
class User {
static hasMany = [ friends: User ]
static mappedBy = [ friends: 'friends' ] //this how you refer to it using GORM as well as Database
String name
String toString() {
name
}
def static constrains () {
name(nullable:false,required:true)
}
def static mapping={
/ / further database custom mappings ,like custom ID field/generation
}
}
def init = {servletContext->
if(User?.list()==null) { // you need to import User class :)
def user = new User(name:"danielad")
def friends= new User(name:'confile')
def friends2=new User(name:'stackoverflow.com')
user.addToFriends(friends)
user.addToFriends(friends2)
user.save(flash:true)
}
}
3#。您的问题在此堆栈溢出链接上重复: 在 Grails 域对象中维护自引用多对多关系的双方
它看起来像多对多关系(一个用户有很多朋友,并且是很多用户的朋友)。因此,解决方案之一是创建新的域类,可以说是 Frendship。然后像这里修改用户域类:
class Friendship {
belongsTo = [
friend1: User
, friend2: User
]
}
class User{
String name
hasMany = [
hasFriends: Friendship
, isFriendOf: Friendship
]
static mappedBy = [
hasFriends: 'friend1'
, isFriendOf: 'frined2'
]
}