I have the following models
type User struct {
gorm.Model
Languages []Language `gorm:"many2many:user_languages;"`
}
type Language struct {
gorm.Model
Name string
Users []User `gorm:"many2many:user_languages;"`
}
and for creating a language I do:
func CreateLanguage(db *gorm.DB, w http.ResponseWriter, r *http.Request) {
language := models.Language{}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&language); err != nil {
respondError(w, http.StatusBadRequest, err.Error())
return
}
defer r.Body.Close()
if err := db.Save(&language).Error; err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusCreated, language)
}
when I check the database, I have the table Language
filled with the language I created, but user_languages
was not filled. I thought gorm
was in charge of updating the intermediate table when you user gorm:"many2many:user_languages;"
, and the engine will figure out how to manage creations.
So question: how to manage creation with gorm
when you have many2many
relationships?
Gorm has a feature to auto save associations and its references from the struct. In your case you need to pass correct JSON object, for example if you pass:
{
"Name": "EN",
"Users": [
{
"ID": 1
}
]
}
Gorm will create new language with name "EN" and join it with the user row found by id 1 by creating new row in user_language table.
Read more about Gorm associations: http://gorm.io/docs/associations.html