考慮以下用戶等級:如何在Grails中實現自引用關係?
class User {
String name
static hasMany = [friends: User]
}
我想,一個用戶可以有很多朋友是哪個用戶正在訪問的類的實例。
如何實現用戶的好友關係?
考慮以下用戶等級:如何在Grails中實現自引用關係?
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#。您的問題在這個堆棧溢出鏈接上重複: Maintaining both sides of self-referential many-to-many relationship in Grails domain object
它看起來像多對多關係(一個用戶有很多朋友,並且是很多用戶的朋友)。所以其中一個解決方案就是創建新的域名類,讓它說成是Frendship。然後修改用戶領域類喜歡這裏:
class Friendship {
belongsTo = [
friend1: User
, friend2: User
]
}
class User{
String name
hasMany = [
hasFriends: Friendship
, isFriendOf: Friendship
]
static mappedBy = [
hasFriends: 'friend1'
, isFriendOf: 'frined2'
]
}
'靜態的hasMany = [網友:用戶]' –
是不是很簡單? – confile
@confile爲什麼它不應該?更多真棒:http://grails.org/doc/latest/guide/GORM.html –