this is what my playlist and user’s models looks like
type Playlist struct {
ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid;default:gen_random_uuid()"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
Title string `json:"title" gorm:"not null"`
// Many 2 many with Back Reference
Users []*User `json:"users" gorm:"many2many:playlist_users"`
}
type User struct {
ID uuid.UUID `json:"id" uri:"id" gorm:"primaryKey;type:uuid;default:gen_random_uuid()"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
Username string `json:"username" gorm:"unique; not null"`
Password string `json:"-" gorm:"not null"`
// Many 2 many with Back Reference
Playlists []*Playlist `json:"playlists" gorm:"many2many:user_playlists;"`
}
and this is what my "create a playlist" handler looks like,
if err := db.GlobalConnection.Create(&playlist).Error; err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, &model.ErrorResponse{
Message: "Failed to create playlist.",
Error: err.Error(),
})
return
}
if err := db.GlobalConnection.Model(&playlist).Association("Users").Append(&user); err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, &model.ErrorResponse{
Message: "Failed to create playlist.",
Error: err.Error(),
})
return
}
the handler only creates playlist_users and not user_playlists too
in order to create user_playlists i would have to add this also,
if err := db.GlobalConnection.Model(&user).Association("Playlists").Append(&playlist); err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, &model.ErrorResponse{
Message: "Failed to create playlist.",
Error: err.Error(),
})
return
}
is this an intended behavior? or am i doing something wrong?
2
Answers
From, what I understand from you code is you want to create many2many relation between user and playlist, if you are doing so than only three tables should exist in your database that is playlists, users and a table consisting primary key of both tables naming either user_playlists or playlist_users whatever you prefer in user you should rename many2many relation table name to playlist_users if you want table name as playlist_users else you can rename it on playlist side many2many relation will create you a table which already satisfies your need so no need to create another table.
I did it this way:
I think you should reference the table that you wan to make relation with, not the table that facilitates the relation.