Golang Gorm 一对多与 has-one
Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《Golang Gorm 一对多与 has-one》带大家来了解一下Golang Gorm 一对多与 has-one,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!
问题内容
我正在尝试通过构建一个小原型订单管理应用程序来学习 Go 和 Gorm。数据库是 MySQL。通过简单的查询,Gorm 一直很出色。然而,当试图获得一个包含一对多和一对一关系组合的结果集时,Gorm 似乎达不到要求。毫无疑问,实际上是我缺乏了解。我似乎无法找到任何我想要完成的在线示例。任何帮助将不胜感激。
去结构
// Order type Order struct { gorm.Model Status string OrderItems []OrderItem } // Order line item type OrderItem struct { gorm.Model OrderID uint ItemID uint Item Item Quantity int } // Product type Item struct { gorm.Model ItemName string Amount float32 }
数据库表
orders id | status 1 | pending order_items id | order_id | item_id | quantity 1 | 1 | 1 | 1 2 | 1 | 2 | 4 items id | item_name | amount 1 | Go Mug | 12.49 2 | Go Keychain | 6.95 3 | Go T-Shirt | 17.99
当前查询
order := &Order if err := db.Where("id = ? and status = ?", reqOrder.id, "pending") .First(&order).Error; err != nil { fmt.Printf(err.Error()) } db.Model(&order).Association("OrderItems").Find(&order.OrderItems)
结果(gorm 进行 2 db 查询)
order == Order { id: 1, status: pending, OrderItems[]: { { ID: 1, OrderID: 1, ItemID: 1, Item: nil, Quantity: 1, }, { ID: 2, OrderID: 1, ItemID: 2, Item: nil, Quantity: 4, } }
替代查询
order := &Order db.Where("id = ? and status = ?", reqOrder.id, "cart") .Preload("OrderItems").Preload("OrderItems.Item").First(&order)
结果(gorm 进行 3 db 查询)
order == Order { id: 1, status: pending, OrderItems[]: { { ID: 1, OrderID: 1, ItemID: 1, Item: { ID: 1, ItemName: Go Mug, Amount: 12.49, } Quantity: 1, }, { ID: 2, OrderID: 1, ItemID: 2, Item: { ID: 2, ItemName: Go Keychain, Amount: 6.95, }, Quantity: 4, } }
理想的结果
上面的“替代查询”会产生理想的查询结果。但是,Gorm 为此进行了 3 个单独的数据库查询。理想情况下,使用 1 个(或 2 个)数据库查询可以获得相同的结果。
这可以通过几个连接在 MySQL 中完成。Gorm 允许连接。但是,我希望利用 Gorm 的一些关系魔法。
非常感谢!
正确答案
如本期所述,gorm 并非旨在使用连接来预加载其他结构值。如果您想继续使用 gorm 并有能力使用连接来加载值,则必须使用gorm 中公开的SQL Builder ,并编写一些代码来扫描所需的值。
如果有许多表需要考虑,这将变得很麻烦。如果[xorm](https://github.com/go- xorm/xorm)作为选项可用,它们支持加载结构值。[在此处](https://github.com/go-xorm/xorm#quick- start)的查找项目符号下进行了描述。
注意:我没有扫描所有字段,仅足以理解要点。
示例 :
package main import ( "log" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" "github.com/kylelemons/godebug/pretty" ) // Order type Order struct { gorm.Model Status string OrderItems []OrderItem } // Order line item type OrderItem struct { gorm.Model OrderID uint ItemID uint Item Item Quantity int } // Product type Item struct { gorm.Model ItemName string Amount float32 } var ( items = []Item{ {ItemName: "Go Mug", Amount: 12.49}, {ItemName: "Go Keychain", Amount: 6.95}, {ItemName: "Go Tshirt", Amount: 17.99}, } ) func main() { db, err := gorm.Open("sqlite3", "/tmp/gorm.db") db.LogMode(true) if err != nil { log.Panic(err) } defer db.Close() // Migrate the schema db.AutoMigrate(&OrderItem{}, &Order{}, &Item{}) // Create Items for index := range items { db.Create(&items[index]) } order := Order{Status: "pending"} db.Create(&order) item1 := OrderItem{OrderID: order.ID, ItemID: items[0].ID, Quantity: 1} item2 := OrderItem{OrderID: order.ID, ItemID: items[1].ID, Quantity: 4} db.Create(&item1) db.Create(&item2) // Query with joins rows, err := db.Table("orders").Where("orders.id = ? and status = ?", order.ID, "pending"). Joins("Join order_items on order_items.order_id = orders.id"). Joins("Join items on items.id = order_items.id"). Select("orders.id, orders.status, order_items.order_id, order_items.item_id, order_items.quantity" + ", items.item_name, items.amount").Rows() if err != nil { log.Panic(err) } defer rows.Close() // Values to load into newOrder := &Order{} newOrder.OrderItems = make([]OrderItem, 0) for rows.Next() { orderItem := OrderItem{} item := Item{} err = rows.Scan(&newOrder.ID, &newOrder.Status, &orderItem.OrderID, &orderItem.ItemID, &orderItem.Quantity, &item.ItemName, &item.Amount) if err != nil { log.Panic(err) } orderItem.Item = item newOrder.OrderItems = append(newOrder.OrderItems, orderItem) } log.Print(pretty.Sprint(newOrder)) }
输出 :
/tmp/main.go.go:55) [2018-06-18 18:33:59] [0.74ms] INSERT INTO "items" ("created_at","updated_at","deleted_at","item_name","amount") VALUES ('2018-06-18 18:33:59','2018-06-18 18:33:59',NULL,'Go Mug','12.49') [1 rows affected or returned ] (/tmp/main.go.go:55) [2018-06-18 18:33:59] [0.50ms] INSERT INTO "items" ("created_at","updated_at","deleted_at","item_name","amount") VALUES ('2018-06-18 18:33:59','2018-06-18 18:33:59',NULL,'Go Keychain','6.95') [1 rows affected or returned ] (/tmp/main.go.go:55) [2018-06-18 18:33:59] [0.65ms] INSERT INTO "items" ("created_at","updated_at","deleted_at","item_name","amount") VALUES ('2018-06-18 18:33:59','2018-06-18 18:33:59',NULL,'Go Tshirt','17.99') [1 rows affected or returned ] (/tmp/main.go.go:58) [2018-06-18 18:33:59] [0.71ms] INSERT INTO "orders" ("created_at","updated_at","deleted_at","status") VALUES ('2018-06-18 18:33:59','2018-06-18 18:33:59',NULL,'pending') [1 rows affected or returned ] (/tmp/main.go.go:61) [2018-06-18 18:33:59] [0.62ms] INSERT INTO "order_items" ("created_at","updated_at","deleted_at","order_id","item_id","quantity") VALUES ('2018-06-18 18:33:59','2018-06-18 18:33:59',NULL,'49','145','1') [1 rows affected or returned ] (/tmp/main.go.go:62) [2018-06-18 18:33:59] [0.45ms] INSERT INTO "order_items" ("created_at","updated_at","deleted_at","order_id","item_id","quantity") VALUES ('2018-06-18 18:33:59','2018-06-18 18:33:59',NULL,'49','146','4') [1 rows affected or returned ] (/tmp/main.go.go:69) [2018-06-18 18:33:59] [0.23ms] SELECT orders.id, orders.status, order_items.order_id, order_items.item_id, order_items.quantity, items.item_name, items.amount FROM "orders" Join order_items on order_items.order_id = orders.id Join items on items.id = order_items.id WHERE (orders.id = '49' and status = 'pending') [0 rows affected or returned ] --- ONLY ONE QUERY WAS USED TO FILL THE STRUCT BELOW 2018/06/18 18:33:59 {Model: {ID: 49, CreatedAt: 0001-01-01 00:00:00 +0000 UTC, UpdatedAt: 0001-01-01 00:00:00 +0000 UTC, DeletedAt: nil}, Status: "pending", OrderItems: [{Model: {ID: 0, CreatedAt: 0001-01-01 00:00:00 +0000 UTC, UpdatedAt: 0001-01-01 00:00:00 +0000 UTC, DeletedAt: nil}, OrderID: 49, ItemID: 145, Item: {Model: {ID: 0, CreatedAt: 0001-01-01 00:00:00 +0000 UTC, UpdatedAt: 0001-01-01 00:00:00 +0000 UTC, DeletedAt: nil}, ItemName: "Go Mug", Amount: 12.489999771118164}, Quantity: 1}, {Model: {ID: 0, CreatedAt: 0001-01-01 00:00:00 +0000 UTC, UpdatedAt: 0001-01-01 00:00:00 +0000 UTC, DeletedAt: nil}, OrderID: 49, ItemID: 146, Item: {Model: {ID: 0, CreatedAt: 0001-01-01 00:00:00 +0000 UTC, UpdatedAt: 0001-01-01 00:00:00 +0000 UTC, DeletedAt: nil}, ItemName: "Go Keychain", Amount: 6.949999809265137}, Quantity: 4}]}
今天带大家了解了golang的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

- 上一篇
- Go 的修订历史背后的故事是什么?

- 下一篇
- 如何获取目录总大小?
-
- 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次学习
-
- 茅茅虫AIGC检测
- 茅茅虫AIGC检测,湖南茅茅虫科技有限公司倾力打造,运用NLP技术精准识别AI生成文本,提供论文、专著等学术文本的AIGC检测服务。支持多种格式,生成可视化报告,保障您的学术诚信和内容质量。
- 83次使用
-
- 赛林匹克平台(Challympics)
- 探索赛林匹克平台Challympics,一个聚焦人工智能、算力算法、量子计算等前沿技术的赛事聚合平台。连接产学研用,助力科技创新与产业升级。
- 93次使用
-
- 笔格AIPPT
- SEO 笔格AIPPT是135编辑器推出的AI智能PPT制作平台,依托DeepSeek大模型,实现智能大纲生成、一键PPT生成、AI文字优化、图像生成等功能。免费试用,提升PPT制作效率,适用于商务演示、教育培训等多种场景。
- 97次使用
-
- 稿定PPT
- 告别PPT制作难题!稿定PPT提供海量模板、AI智能生成、在线协作,助您轻松制作专业演示文稿。职场办公、教育学习、企业服务全覆盖,降本增效,释放创意!
- 91次使用
-
- Suno苏诺中文版
- 探索Suno苏诺中文版,一款颠覆传统音乐创作的AI平台。无需专业技能,轻松创作个性化音乐。智能词曲生成、风格迁移、海量音效,释放您的音乐灵感!
- 91次使用
-
- 老师代码没有自动跟踪?
- 2023-03-07 439浏览
-
- c程序fork并等待golang进程状态
- 2023-03-05 262浏览
-
- GOLANG使用Context管理关联goroutine的方法
- 2022-12-28 193浏览
-
- 怎么用Golang将MySQL表转储为JSON
- 2023-03-07 188浏览
-
- Golang 检查字符串是否为有效路径?
- 2023-03-10 500浏览