'GORM creates duplicates on many2many
I am using GORM in my Go Gin API and want to create an association between my User and the Role table. So far, I have simply followed the documentation, but I am running into a problem. Here are my used models:
type User struct {
gorm.Model
FirstName string
LastName string
Email string `gorm:"unique"`
Password []byte
Roles []Role `gorm:"many2many:user_roles"`
}
type Role struct {
gorm.Model
Name string
}
While I'm still developing, I want to write data directly to the database when I start the API. For this I create the following:
Db.Create(&User{
FirstName:"Jon",
LastName:"Doe",
Email: "[email protected]",
Password: encoded,
Roles: []Role{
{Name: "admin"},
{Name: "service"},
},
})
Db.Create(&User{
FirstName:"Jon",
LastName:"Doe",
Email: "[email protected]",
Password: encoded,
Roles: []Role{
{Name: "admin"},
{Name: "service"},
},})
This way I want each name to appear only once in the role table. The corresponding ID should be used in the automatically created user_roles table each time such an entry is created. What happens, however, is this: Roles Table:
| id | name |
|---|---|
| 1 | admin |
| 2 | service |
| 3 | admin |
| 4 | service |
User_Role Table:
| user_id | role_id |
|---|---|
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
| 2 | 4 |
I have read through https://gorm.io/docs/associations.html and tried Omit but nothing worked yet. I hope someone has an idea or already solved the same problem. Thanks a lot!
Edit: When trying "try sending just the role IDs instead of role names" i do it like this:
Db.Create(&User{
FirstName:"Jon",
LastName:"Doe",
Email: "[email protected]",
Password: encoded,
Roles: []Role{
{ID: 1},
{ID: 2},
},})
This gives me the error
cannot use promoted field Model.ID in struct literal of type Role
2. Edit The ID needs to be listed seperated in the Role model, it does not work just with the gorm.Model
type Role struct {
gorm.Model
ID uint `gorm:"primarykey"`
Name string
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
