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?
how should I define then the structure of the user_languages table?
You should also describe the user_languages
model for many2many relations like User
and Language
as example
type UserLanguages struct {
gorm.Model
UserId int
LanguageId int
}
And probably you should define primary keys for User
and Language
models
how the foreign keys are set there?
GORM generates names of foreign keys in queries yourself, in underscore format (like user_id
, language_id
), for redefining it you can use special AssociationForeignKey
annotation on model fields, I hope it will help!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.