Having issues with many2many, I went back to the documentation and tried to make the first example work.
// User has and belongs to many languages, `user_languages` is the join table
type User struct {
gorm.Model
Languages []Language `gorm:"many2many:user_languages;"`
}
type Language struct {
gorm.Model
Name string
}
gorm-playground has similar code so I just had to slightly modify models.go with
type Language struct {
gorm.Model
Code string
Name string
}
and main_test.go by adding
DB.Model(&result).Association("Languages").Append(&Language{
Code: "en-us",
Name: "English",
})
at the end of TestGORM.
I tested with mysql, postgres & sqlite. It went great.
Then I duplicated the code in TestGORM to add a second user speaking the same language.
a) as is, I ended up (same test matrix: mysql, postgres & sqlite) with 2 identical Language records which is not what I expected.
b) so I added a gorm annotation to Code => gorm:"size:64;uniqueIndex"
This time, gorm asked the db to INSERT ... ON CONFLICT DO NOTHING RETURNING id (postgres & sqlite), ON DUPLICATE KEY UPDATE id=id (mysql).
But then trying to create the join table record, the db sets language_id to 0 (the original en-us record being id=1) which expectedly failed (FOREIGN KEY constraint).
I'd love to know what I'm missing as I'm out of ideas. It feels like gorm isn't getting id back after the "insert conflict".