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问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 美图AI抠图
- 美图AI抠图,依托CVPR 2024竞赛亚军技术,提供顶尖的图像处理解决方案。适用于证件照、商品、毛发等多场景,支持批量处理,3秒出图,零PS基础也能轻松操作,满足个人与商业需求。
- 13次使用
-
- PetGPT
- SEO摘要PetGPT 是一款基于 Python 和 PyQt 开发的智能桌面宠物程序,集成了 OpenAI 的 GPT 模型,提供上下文感知对话和主动聊天功能。用户可高度自定义宠物的外观和行为,支持插件热更新和二次开发。适用于需要陪伴和效率辅助的办公族、学生及 AI 技术爱好者。
- 14次使用
-
- 可图AI图片生成
- 探索快手旗下可灵AI2.0发布的可图AI2.0图像生成大模型,体验从文本生成图像、图像编辑到风格转绘的全链路创作。了解其技术突破、功能创新及在广告、影视、非遗等领域的应用,领先于Midjourney、DALL-E等竞品。
- 42次使用
-
- MeowTalk喵说
- MeowTalk喵说是一款由Akvelon公司开发的AI应用,通过分析猫咪的叫声,帮助主人理解猫咪的需求和情感。支持iOS和Android平台,提供个性化翻译、情感互动、趣味对话等功能,增进人猫之间的情感联系。
- 39次使用
-
- Traini
- SEO摘要Traini是一家专注于宠物健康教育的创新科技公司,利用先进的人工智能技术,提供宠物行为解读、个性化训练计划、在线课程、医疗辅助和个性化服务推荐等多功能服务。通过PEBI系统,Traini能够精准识别宠物狗的12种情绪状态,推动宠物与人类的智能互动,提升宠物生活质量。
- 36次使用
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览