0

So essentially I have two classes:

Class User {
  String Name
}
Class Project {
  User requestedBy
    static hasMany =
    [
      assignedTo: User  
    ]
}

Now, I can set the requestedBy to say, User 1. I can also do Project.addToAssignedTo(User 1).

The problem comes when I want to remove the user from assigned to when they already exist as the requestedBy. I can remove other users without problem:

Project.removeFromAssignedTo(User 1).save(failOnError: true, flush: true)

I get no errors of any kind, the data just simply does not get removed. Any help would be appreciated!

Thanks!

James Kleeh
  • 12,094
  • 5
  • 34
  • 61

1 Answers1

0

When defining multiple relationships to the same class, you should define the bidirectional relationship, and use the mappedBy property to define both sides of that relationship:

class User {
  String Name

  hasMany = [requestedProjects: Project, assignedProjects: Project]

}
class Project {
  User requestedBy
    static hasMany =
    [
      assignedTo: User  
    ]

    static mappedBy = [requestedBy: 'requestedProjects', assignedTo: 'assignedProjects']

}

Hopefully that solves your problem.

OverZealous
  • 39,252
  • 15
  • 98
  • 100
  • It complained about an owner not begin defined. I defined the owner and it still gave the same error. Really though there shouldn't be an owner. A project isnt owned by a single person, and certainly a user is not owned by a project. Any ideas? – James Kleeh Apr 11 '12 at 12:52
  • `belongsTo` doesn't imply one-to-many or one-to-one. It has more to do with defining the "responsible" domain class. The `belongsTo` class is the one that is responsible for saving relationships in a many-to-many. See [the docs for more](http://grails.org/doc/2.0.x/ref/Domain%20Classes/belongsTo.html). Try adding `belongsTo` to the `Project` class, and see if that helps. `static belongsTo = [requestedBy: User, assignedTo: User]` – OverZealous Apr 11 '12 at 16:49