2

I have a question about how to save M2M relations. One side must be always the owning side. In our scenario we have a entity "Role" and a entity "User". A Role can have many users and users can be assigned to different roles. The "Role" entity is the owning site.

In the Gui the Administrator can add users to a role. When I save the role with the assigned users everything works well. Now we should provide a way to assign roles to users. The Gui for this is no problem but I don't know how to save the changed role assignments. Saving the user doesn't save the assigned roles because it is not the owning side.

Is there another way to do this? I'm not sure but I think the only way to do this is to add the selected user to all assigned roles and save the roles.

1 Answers1

0

To save the association you will need to save the owning side of the relationship. In order to keep things consistent for in-memory objects, you will probably want to manage this in a service method that updates the collections in the user and the role and (if it makes sense in your implementation) performs the save for you, then you can call the method to make the association whether you are adding a user to a role or a role to a user. That will at least abstract the model implementation away from the callers of your service and make sure things are persisted properly.

digitaljoel
  • 26,265
  • 15
  • 89
  • 115
  • Ok, thanks for your answer. I've tried to save the role assignment in the service layer. Here is my example: –  Mar 11 '11 at 16:53
  • User has one role assigned. In the Gui I remove this role assignment. When the Admin clicks on save my service method is called. In this method I try to delete the role relation of the user. The user.getRoles() is empty (as expected). To delete the relation in databaae I try to load the role from the databaae, remove the user and save the role. Heres my problem. The loaded role doesn't contains the user, but it is stored in database. So I cannot delete the relation. –  Mar 11 '11 at 17:11
  • Perhaps your role is cached. Can you purge the role from the cache and reload it to make sure it reflects what is really in the database then perform your operation? – digitaljoel Mar 11 '11 at 21:38
  • Yes. Thats the problem. I cannot read the role from database. I always retrieve the cached instance. I will try your hint tomorrow. –  Mar 13 '11 at 20:18