Gorm 协会多对多
GORM 多对多关联通常会创建一个联接表,但如果需要一个带有附加字段的自定义联接表,则无法直接实现。本文介绍了一种替代方法,将多对多关系拆分为两个“有一”和两个一对多关系,从而创建一个“一流”的中间模型。这种方法允许在中间模型中添加额外的属性,例如次数和组数,并通过预加载功能轻松访问关联数据。
我知道 gorm 多对多关联会创建一个联接表,但是如果我想要/需要一个带有附加字段的自定义联接表怎么办
我的例子如下
所以我有两个 gorm 模型
type Exercise struct {
gorm.Model
Name string `gorm:"not null" json:"name"`
Description string `gorm:"not null json:"description"`
}
type Workout struct {
gorm.Model
Name string `gorm:"not null" json:"name"`
CreatedAt time.Time `gorm:"not null" json:"created_at"`
}
如果我使用 gorm 多对多关联,它将创建一个锻炼锻炼连接表,但我将如何确保填写其他字段(例如次数和组数)。这是需要在控制器中完成的事情,而不是真正由 gorm 处理的事情。我已经用 nodejs 和 sequelize 做了类似的事情,但对于 go 和 gorm 世界来说确实是新的。
解决方案
参加聚会有点晚了,但是......我的目标是创造类似的东西,在花了一整天的时间之后,碰壁了,退后一步重新思考......
经过一番深思熟虑,考虑了很多游戏以及朋友的良好建议,我们决定从稍微不同的角度进行处理。
如果您以不同的方式看待它,您可以将其“改写”为两个“有一”(或属于“属于”)和两个一对多,而不是多对多:
- 锻炼有多种锻炼方式
- 锻炼有很多锻炼活动
- workout-exercise 包含锻炼和一项练习
此外,在我的游戏过程中,我意识到多对多表的属性(列)没有在上面模型中的任何地方引用,因此它无论如何都没有用。
如果您将锻炼-锻炼视为“一流”模型,那么它开始变得更有意义并且变得更有用:
- 您可以创建练习 - 它是一种静态资源池
- 您可以创建锻炼
- 然后,您可以使用锻炼-锻炼模型将练习填充到锻炼中。
总而言之,我的建议如下:
type exercise struct {
gorm.model
name string `gorm:"not null" json:"name"`
description string `gorm:"not null" json:"description"`
workouts []workoutexercise
}
type workout struct {
gorm.model
name string `gorm:"not null" json:"name"`
createdat time.time `gorm:"not null" json:"created_at"`
exercises []workoutexercise
}
type workoutexercise struct {
gorm.model
workoutid uint
workout workout `gorm:"foreignkey:workoutid;references:id"`
exerciseid uint
exercise exercise `gorm:"foreignkey:exerciseid;references:id"`
sets uint
reps uint
weights uint
}
它产生以下模式(我相信这是所需要的):
gym=# \dt
list of relations
schema | name | type | owner
--------+-------------------+-------+-----------
public | installations | table | gym
public | workout_exercises | table | gym
public | workouts | table | gym
(3 rows)
gym=# \d workouts
table "public.workouts"
column | type | collation | nullable | default
------------+--------------------------+-----------+----------+--------------------------------------
id | bigint | | not null | nextval('workouts_id_seq'::regclass)
created_at | timestamp with time zone | | not null |
updated_at | timestamp with time zone | | |
deleted_at | timestamp with time zone | | |
name | text | | not null |
indexes:
"workouts_pkey" primary key, btree (id)
"idx_workouts_deleted_at" btree (deleted_at)
referenced by:
table "workout_exercises" constraint "fk_workouts_exercises" foreign key (workout_id) references workouts(id)
gym=# \d exercises
table "public.exercises"
column | type | collation | nullable | default
-------------+--------------------------+-----------+----------+---------------------------------------
id | bigint | | not null | nextval('exercises_id_seq'::regclass)
created_at | timestamp with time zone | | |
updated_at | timestamp with time zone | | |
deleted_at | timestamp with time zone | | |
name | text | | not null |
description | text | | not null |
indexes:
"exercises_pkey" primary key, btree (id)
"idx_exercises_deleted_at" btree (deleted_at)
referenced by:
table "workout_exercises" constraint "fk_exercises_workouts" foreign key (exercise_id) references exercises(id)
gym=# \d workout_exercises
table "public.workout_exercises"
column | type | collation | nullable | default
-------------+--------------------------+-----------+----------+-----------------------------------------------
id | bigint | | not null | nextval('workout_exercises_id_seq'::regclass)
created_at | timestamp with time zone | | |
updated_at | timestamp with time zone | | |
deleted_at | timestamp with time zone | | |
workout_id | bigint | | |
exercise_id | bigint | | |
sets | bigint | | |
reps | bigint | | |
weights | bigint | | |
indexes:
"workout_exercises_pkey" primary key, btree (id)
"idx_workout_exercises_deleted_at" btree (deleted_at)
foreign-key constraints:
"fk_exercises_workouts" foreign key (exercise_id) references exercises(id)
"fk_workouts_exercises" foreign key (workout_id) references workouts(id)
如果您考虑一下,在没有附加属性的情况下进行锻炼是没有意义的。如果您只想获取锻炼的练习,您可以从中间模型中提取它*:
workout := Workout
db.Preload("WorkoutExercise.Exercise").First(&workout, 10)
for _, we := range workout.Exercises {
// access reps, etc directly from we
// and access the exercise from the property we.Exercise
log.Printf("do %d sets of %d repetitions of %s", we.Sets, we.Reps,
we.Exercise.Name)
}
*免责声明 - 尚未实际运行此代码(其余部分有效)。请查看 Nested Preloading 以实现一些深度嵌套的预加载。
理论要掌握,实操不能落!以上关于《Gorm 协会多对多》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
在矩形内取随机坐标避免重叠
- 上一篇
- 在矩形内取随机坐标避免重叠
- 下一篇
- 从 Go 中提取 Unicode 脚本符文
-
- Golang · Go问答 | 8分钟前 |
- Go time.ParseDuration 遇到中文或复合单位输入怎么给出明确错误
- 107浏览 收藏
-
- Golang · Go问答 | 8分钟前 | Go问答 · Go Equal 时间比较 time.Time.Round 单调时钟 Compare
- Go time.Time.Round 后比较结果为什么和原值不同
- 195浏览 收藏
-
- Golang · Go问答 | 13分钟前 |
- Go time.Parse 为什么要把时区布局写成 -0700
- 422浏览 收藏
-
- Golang · Go问答 | 16分钟前 | Go问答 · 配置文件 Go os.OpenFile O_EXCL O_CREATE
- Go os.OpenFile 怎么避免并发创建配置文件时互相覆盖
- 174浏览 收藏
-
- Golang · Go问答 | 17分钟前 | 文件读取 · Go问答 · Go io.SectionReader 大文件分段读取 范围导出
- Go io.SectionReader 怎么把大文件的一段导出成独立 Reader
- 347浏览 收藏
-
- Golang · Go问答 | 19分钟前 |
- Go io.CopyN 源数据不足时怎么区分 EOF 和写入错误
- 160浏览 收藏
-
- Golang · Go问答 | 21分钟前 | 配置管理 · Go问答 · Go os.UserConfigDir 跨平台配置 用户配置目录
- Go os.UserConfigDir 在不同系统上怎么确定配置文件目录
- 219浏览 收藏
-
- Golang · Go问答 | 26分钟前 | Go问答 · Go UTF-8 unicode/utf8 DecodeRune
- Go utf8.DecodeRune 遇到非法字节时怎么避免循环不前
- 380浏览 收藏
-
- Golang · Go问答 | 26分钟前 | go ·
- Go csv.Reader 遇到列数不一致时怎么保留异常行
- 248浏览 收藏
-
- Golang · Go问答 | 27分钟前 |
- Go testing.T.Chdir 在子测试中为什么会影响父测试
- 480浏览 收藏
-
- Golang · Go问答 | 34分钟前 | 标准库 · go · csv · csv Go encoding/csv TrimLeadingSpace
- Go csv.Reader TrimLeadingSpace 处理字段前导空格的规则与引号边界
- 248浏览 收藏
-
- Golang · Go问答 | 2天前 | 并发 · go · 初始化 · Go 初始化错误 sync.OnceValue 并发排障
- OnceValue 初始化错误缓存后的恢复策略
- 500浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 446次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 517次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 532次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 478次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 303次使用
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go crypto/rand.Text 的长度为什么不是固定字符数
- 2026-10-04 501浏览
-
- Go strings.ToValidUTF8 清洗日志内容的边界
- 2026-10-03 501浏览
-
- Go tls.GetCertificate 为什么收不到空 ServerName 请求
- 2026-09-27 501浏览

