如何在Grails中实现自引用关系?

时间:2013-07-15 11:49:04

标签: grails grails-2.0 grails-domain-class

给出以下User类:

class User {

  String name

  static hasMany = [friends: User]
}

我希望用户可以拥有许多朋友,这些朋友都是用户域类的实例。

我如何实现用户的朋友关系?

2 个答案:

答案 0 :(得分:4)

1。你如何定义关系

     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   
     }
    }

2.如何保存数据:

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

答案 1 :(得分:0)

它看起来像多对多关系(一个用户有很多朋友,并且是很多用户的朋友)。所以其中一个解决方案就是创建新的域类,让我们说它是Frendship。然后像这里修改用户域类:

class Friendship {
    belongsTo = [
        friend1: User
        , friend2: User
    ]
}

class User{
    String name
    hasMany = [
        hasFriends: Friendship
        , isFriendOf: Friendship
    ]

    static mappedBy = [
            hasFriends: 'friend1'
            , isFriendOf: 'frined2'
    ]
}