Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails Many-To-Many and One-To-Many clash

I have the following two domain classes, User and Posts And I have two relationships between them, User has 1-to-many with Posts with back reference. User has many-to-many relationships with posts that he follows: The relationships I've got are as follows:

User {
hasMany = [posts : Post, followingPosts: Post]
belongsTo = [Post] //For the many-to-many, this is the owner i'd like to have.

}

Post {
  hasMany = [followers: User]
  belongsTo = [owner: User] //For the 1-to-Many, this is my back-reference
}

Now I'm getting a clash with Grails, I tried solving it through mapping but with no success, this is the error I get :

    Domain classes [Post] and [User] cannot own each other in a many-to-many relationship. Both   contain belongsTo definitions that reference each other. (Use --stacktrace to see the full trace)

Anyone know how to resolve this ?

like image 575
user1847198 Avatar asked Nov 13 '22 17:11

user1847198


1 Answers

I think you can do it using mappedBy, like:

class User{

  static hasMany = [posts : Post, followingPosts: Post]
  static mappedBy = [posts : "user"]
}


class Post{  

  User user
  static hasMany = [followers: User]
  static belongsTo = User
}

Take a look at this for more info about the mappedBy.

like image 91
Tiago Farias Avatar answered Nov 15 '22 06:11

Tiago Farias