【问题标题】:How to implement Self-Referencing Relationships in Grails?如何在 Grails 中实现自引用关系?
【发布时间】:2013-07-15 11:49:04
【问题描述】:

给定以下用户类:

class User {

  String name

  static hasMany = [friends: User]
}

我希望一个用户可以有很多朋友,这些朋友是用户域类的实例。

如何实现用户的好友关系?

【问题讨论】:

  • static hasMany = [friends: User]
  • @confile 为什么不应该这样做?更棒的是:grails.org/doc/latest/guide/GORM.html
  • 如果您发布我可以接受的答案。如何添加或删除好友?我必须做 user1.addToFriends(user2) 和 user2.addToFriends(user1) 还是只做其中一个?
  • @confile 咬手指。你不是在做梦。 ;)
  • @dmahapatro 你这是什么意思?

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    看起来像是多对多的关系(一个用户有很多朋友,并且是很多用户的朋友)。因此,解决方案之一是创建新的域类,可以说是 Frendship。然后像这里修改用户域类:

    class Friendship {
        belongsTo = [
            friend1: User
            , friend2: User
        ]
    }
    
    class User{
        String name
        hasMany = [
            hasFriends: Friendship
            , isFriendOf: Friendship
        ]
    
        static mappedBy = [
                hasFriends: 'friend1'
                , isFriendOf: 'frined2'
        ]
    }
    

    【讨论】:

      猜你喜欢
      • 2022-07-08
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      • 1970-01-01
      • 2018-01-14
      • 2013-03-14
      相关资源
      最近更新 更多