Michael
Michael

Reputation: 33297

How to implement Self-Referencing Relationships in Grails?

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?

Upvotes: 4

Views: 2788

Answers (2)

Daniel Wondyifraw
Daniel Wondyifraw

Reputation: 7713

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

Upvotes: 4

kpater87
kpater87

Reputation: 1270

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

Upvotes: 0

Related Questions