define associative model in Golang gorm

2019-08-24 13:58发布

问题:

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?

回答1:

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!



标签: go go-gorm