Issue with many-to-many and mapping
This is my first project with many-to-many relationship and after reading some grails stuff of ORM, I decided to let grails do the work for me, like creating the tables. Actually, my deal was:
- 1 User has many Groups
- 1 Group belongs to an User and has many Users(except the owner)
Here are my classes:
class User {
String name
List groups
static hasMany = [groups : Group]
static mapping = {
table 'users'
version false
}
}
class Group {
String name
List members
static belongsTo = User
static hasMany = [members : User]
static mapping = {
table 'groups'
version false
}
}
After that, what I got from grails was 3 tables. The users table was ok, but the next 2 wasn't what I expected.
table **groups** | id | name
table **users_groups** | group_id | user_id | members_idx | groups_idx
Well, what I wanted was something like this:
table **groups** | id | name | user_id
table **users_groups** | group_id | members_idx | groups_idx
I don't know if I did something wr开发者_StackOverflowong or how can I fix it, but anyway... I'm still getting another problem when I try to do user.addToGroups(new Group()) . My users_groups table duplicates this register, one with the members_idx null, and the other register with the groups_idx null.
How about removing belongsTo from group and leave hasMany:
class User {
String name
List groups
static hasMany = [groups : Group]
static mapping = {
table 'users'
version false
}
}
class Group {
String name
List members
static hasMany = [members : User]
static mapping = {
table 'groups'
version false
}
}
EDIT I think You have to make a domain class which will actually join groups and users. I think You should try this:
class User {
String name
static hasMany = [groups : UsersGroups]
static mapping = {
table 'users'
version false
}
}
class Group {
String name
static hasMany = [members : UsersGroups]
static mapping = {
table 'groups'
version false
}
}
class UsersGroups {
static belongsTo = [group: Group, user: User]
static mapping = {
version false
}
}
It will create another table which actually joins groups and users.
If you change the belongsTo to use Map syntax it will use a foreign key and not a join table:
static belongsTo = [user: User]
and you'll have a user
field as a back-reference.
I have done a similar issue before, so I think this may work:
class User {
String name
hasMany = [groups : Group]
static mapping = {
table 'users'
version false
}
}
class Group {
String name
static belongsTo = [owner : User]
static hasMany = [members : User]
static mapping = {
table 'groups'
version false
}
}
About the problem with user.addToGroups
, I think that you should set the owner when creating the group first. Then add other users to group.
精彩评论