在Golang gorm中定义关联模型 [英] define associative model in Golang gorm

查看:180
本文介绍了在Golang gorm中定义关联模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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 模型

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
}

也许您应该为 User Language 模型定义主键

And probably you should define primary keys for User and Language models

如何在其中设置外键?

how the foreign keys are set there?

GORM会自己在查询中以下划线格式(例如 user_id language_id )生成外键名称,为重新定义外键,您可以使用特殊的 AssociationForeignKey 在模型字段上的注释,希望对您有所帮助!

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!

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆