问题描述

我在RestFul服务中使用golang gorm,但是,我现在怀疑这可能很简单,但是我找不到任何示例或特定文档,这对我来说并不明确.

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.

比方说,我有表用户和语言,任何用户都可以有多种语言,任何语言都可以有许多用户,在这种情况下,对于关系数据库建模理论,我们必须创建一个表users_languages,并检查gorm,我看到了我将不得不使用多对多关系.

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
}

然后我运行迁移,并创建了表User和Language.我的问题是,我该如何定义user_languages表的结构?在那里如何设置外键?

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?

推荐答案

那我该如何定义user_languages表的结构?

how should I define then the structure of the user_languages table?

 User  Language  user_languages 
user_languagesUserLanguage
type UserLanguages struct {
    gorm.Model
    UserId int
    LanguageId int
}
 User  Language 
UserLanguage

如何在其中设置外键?

how the foreign keys are set there?

 user_id  language_id  AssociationForeignKey 
user_idlanguage_idAssociationForeignKey

这篇关于在Golang gorm中定义关联模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!