How to implement Self-Referencing Relationships in Grails?

落花浮王杯 提交于 2019-12-10 17:34:59

问题


Given the following User class:

class User {

  String name

  static hasMany = [friends: User]
}

I want that a User can have many friends which are instances of the user domain class.

How do I have to implement the friend relationship of a user?


回答1:


1. How Do you Define the relathionship

     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.How to save Data:

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# . Your question is repeated on this stack overflow link : Maintaining both sides of self-referential many-to-many relationship in Grails domain object




回答2:


It looks like many-to-many relationship (one user has a lot of friends, and is a friend of a lot of users). So one of the solution will be to create new domain class, lets say it Frendship. And then modify User domain class like here:

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

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

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


来源:https://stackoverflow.com/questions/17653567/how-to-implement-self-referencing-relationships-in-grails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!