I am using golang gorm in my RestFul service, however, now I have a doubt that might be simple but I cannot find any example or specific documentation, its not clear to me.
Let's say that I have the tables users and languages, any user can have many languages and any language can have many users, in this case for theory of relational database modeling we have to create a table users_languages, and checking gorm I see that I will have to use many to many relationship.
By now, I have the structs that define the user and language tables, lets say:
type User struct {
gorm.Model
Languages []Language `gorm:"many2many:user_languages;"`
}
type Language struct {
gorm.Model
Name string
}
Then I ran the migrations and the tables User and Language were created. My question is, how should I define then the structure of the user_languages table? how the foreign keys are set there?
You should also describe the
user_languages
model for many2many relations likeUser
andLanguage
as exampleAnd probably you should define primary keys for
User
andLanguage
modelsGORM generates names of foreign keys in queries yourself, in underscore format (like
user_id
,language_id
), for redefining it you can use specialAssociationForeignKey
annotation on model fields, I hope it will help!