在Golang的gorm中定义关联模型。

huangapple go评论129阅读模式
英文:

define associative model in Golang gorm

问题

我正在使用golang的gorm库在我的RestFul服务中,但是现在我有一个疑问,可能很简单,但我找不到任何示例或具体的文档,对我来说不太清楚。

假设我有用户(users)和语言(languages)两个表,任何用户都可以有多种语言,任何语言也可以有多个用户。根据关系数据库建模的理论,我们需要创建一个名为users_languages的表,并且根据我查看的gorm文档,我需要使用多对多关系。

目前,我已经定义了定义用户和语言表的结构体,如下所示:

type User struct {
    gorm.Model
    Languages         []Language `gorm:"many2many:user_languages;"`
}

type Language struct {
    gorm.Model
    Name string
}

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

英文:

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

得分: 1

你应该像示例中的UserLanguage一样,为user_languages表定义user_languages模型,以描述多对多关系。

type UserLanguages struct {
    gorm.Model
    UserId     int
    LanguageId int
}

而且,你可能还应该为UserLanguage模型定义主键。

关于外键的设置,GORM会自动生成查询中的外键名称,采用下划线格式(例如user_idlanguage_id)。如果你想重新定义它,可以在模型字段上使用特殊的AssociationForeignKey注释。希望这对你有帮助!

英文:

> 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!

huangapple
  • 本文由 发表于 2017年9月8日 05:30:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/46105380.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定