define associative model in Golang gorm

我只是一个虾纸丫 提交于 2019-12-11 15:13:09

问题


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!



来源:https://stackoverflow.com/questions/46105380/define-associative-model-in-golang-gorm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!