当前位置:网站首页>【GORM】模型关系-HasMany关系
【GORM】模型关系-HasMany关系
2022-08-09 21:54:00 【Viva Python】
一、概述
HasMany与另一个模型建立一对多的连接,拥有者可以拥有零个或多个关联模型。
二、模型建立
依旧以User和CreditCard为例,一个User可以拥有多张CreditCard。HasMany关系模型的实现主要在拥有者模型中定义。
1. 拥有者模型
实现
HasMany模型,拥有者需要拥有以下字段:(1) 外键:默认为被拥有者的主键,在被拥有者模型中定义,在被拥有者模型切片变量中标注。
(2) 引用:默认为拥有者的主键,在拥有者模型中定义,在被拥有者模型切片变量中标注。
(3) 被拥有者模型切片变量;
以下是拥有者模型
User的定义:以
CreditCard模型中的UserID作为外键,以ID作为索引(默认)。type User struct { ID uint `gorm:"primary_key"` Name string Password string `gorm:"<-;->:false"` CreditCards []CreditCard `gorm:"foreignKey:UserID;references:ID"` }
2. 被拥有者模型(关联模型)
实现
HasMany模型,被拥有者按照正常的逻辑定义,必要时可以添加拥有者模型的外键,如上User模型中使用CreditCard模型中的UserID变量作为外键。与上
User对应的CreditCard模型如下:type CreditCard struct { ID uint `gorm:"primary_key"` UserID uint `gorm:"->:false;<-"` Number string }
三、相关操作
1. 创建
- 定义完整的实例对象,调用
Save方法保存。
func TestSaveUser() {
user := User{
Name: "Jason",
Password: "123",
CreditCards: []CreditCard{
{
Number: "1234567890"},
{
Number: "0987654321"},
},
}
err := SaveUser(user)
if err != nil {
log.Println("用户保存失败!")
} else {
log.Println("用户保存成功!")
}
}
func SaveUser(user User) error {
var err error
err = db.Save(&user).Error
return err
}
2. 查询
- 需要加载关联模型,使用
Preload方法。
func GetUserByName(name string) (User, error) {
var user User
var err error
err = db.Where("name = ?", name).Preload("CreditCards").First(&user).Error
return user, err
}
3. 添加关联模型实例
- 向已有的记录添加关联模型实例,如向已有的
User记录添加CreditCard记录。
func AppendCardByUser(user User, card CreditCard) error {
var err error
err = db.Model(&user).Association("CreditCards").Append(&card)
return err
}
其中Association方法的参数为要添加的关联模型类型,对应关联模型的切片变量名。
边栏推荐
- 埃氏筛选法:统计素数个数
- Sudoku | Backtrack-7
- L3-2 Delete up to three characters (30 points)
- 技术分享 | 接口自动化测试如何处理 Header cookie
- Leetcode 93 IP addresses
- The overall construction process of the Tensorflow model
- Leetcode 93 复原IP地址
- Technology Sharing | How to Handle Header Cookies in Interface Automation Testing
- The round functions in the np, ceil function and floor function
- PHP 二维数组根据某个字段排序
猜你喜欢

五星控股汪建国:以“植物精神”深耕赛道,用“动物精神”推动成长

MLOps的演进历程

Basic JSON usage

Chatting embarrassing scenes, have you encountered it?Teach you to get the Doutu emoticon package with one click, and become a chat expert

AI Knows Everything: Building and Deploying a Sign Language Recognition System from Zero

任务流执行器是如何工作的?

聊天尬死名场面,你遇到过吗?教你一键获取斗图表情包,晋升聊天达人
6 rules to sanitize your code

nvm下node安装;node环境变量配置

几种绘制时间线图的方法
随机推荐
孙正义亏掉1500亿:当初投贵了
In programming languages, the difference between remainder and modulo
BulkInsert方法实现批量导入
CVPR22 Oral|通过多尺度token聚合分流自注意力,代码已开源
接口自动化测试实践指导(上):接口自动化需要做哪些准备工作
发送激活邮件「建议收藏」
Evolution of MLOps
台风生成,广州公交站场积极开展台风防御安全隐患排查
PHP 2D array sorted by a field
Liver all night to write a thirty thousand - word all the commands the SQL database, function, speaks clearly explain operators, content is rich, proposal collection + 3 even high praise!
任务流执行器是如何工作的?
Jinshanyun earthquake, the epicenter is in bytes?
JSON 基本使用
Shanghai Konan SmartRocket series product introduction (3): SmartRocket iVerifier computer interlocking system verification tool
SecureCRT sets the timeout period for automatic disconnection
Simple questions peek into mathematics
Technology Sharing | How to use the JSON Schema mode of interface automation testing?
This article lets you quickly understand implicit type conversion [integral promotion]!
1215 – Cannot add foreign key constraint
Use convert_to_tensor in Tensorflow to specify the type of data