Golang gorm 一对一关系

一对一关系


一对一关系比较少,一般用于表的扩展例如一张用户表,有很多字段那么就可以把它拆分为两张表,常用的字段放主表,不常用的字段放详情表。

针对用户表来说可以通过user去点出userinfo。

创建表和插入数据

Go 复制代码
package main

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Teacher struct {
	ID          int
	Name        string
	Age         int
	Gender      bool
	TeacherInfo TeacherInfo
}

type TeacherInfo struct {
	ID        int
	TeacherID int
	Address   string
	Hobby     string
}

func (*Teacher) TableName() string {
	return "teacher"
}

func (*TeacherInfo) TableName() string {
	return "teacherinfo"
}

func main() {
	dsn := "root:7PXjAkY!&nlR@tcp(192.168.11.128:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
	db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	db.Debug().AutoMigrate(&Teacher{}, &TeacherInfo{})

	var teacherList []Teacher
	teacherList = append(teacherList, Teacher{
		Name:   "yanzi",
		Age:    28,
		Gender: false,
		TeacherInfo: TeacherInfo{
			Address: "hangzhou",
			Hobby:   "video",
		},
	}, Teacher{
		Name:   "lucas",
		Age:    30,
		Gender: false,
		TeacherInfo: TeacherInfo{
			Address: "hangzhou",
			Hobby:   "reading",
		},
	})

	db.Create(&teacherList)

}


mysql> desc teacher;
+--------+------------+------+-----+---------+----------------+
| Field  | Type       | Null | Key | Default | Extra          |
+--------+------------+------+-----+---------+----------------+
| id     | bigint     | NO   | PRI | NULL    | auto_increment |
| name   | longtext   | YES  |     | NULL    |                |
| age    | bigint     | YES  |     | NULL    |                |
| gender | tinyint(1) | YES  |     | NULL    |                |
+--------+------------+------+-----+---------+----------------+

mysql> desc teacherinfo;
+------------+----------+------+-----+---------+----------------+
| Field      | Type     | Null | Key | Default | Extra          |
+------------+----------+------+-----+---------+----------------+
| id         | bigint   | NO   | PRI | NULL    | auto_increment |
| teacher_id | bigint   | YES  | MUL | NULL    |                |
| address    | longtext | YES  |     | NULL    |                |
| hobby      | longtext | YES  |     | NULL    |                |
+------------+----------+------+-----+---------+----------------+

mysql> select * from teacher;
+----+-------+------+--------+
| id | name  | age  | gender |
+----+-------+------+--------+
|  1 | yanzi |   28 |      0 |
|  2 | lucas |   30 |      0 |
+----+-------+------+--------+

mysql> select * from teacherinfo;
+----+------------+----------+---------+
| id | teacher_id | address  | hobby   |
+----+------------+----------+---------+
|  1 |          1 | hangzhou | video   |
|  2 |          2 | hangzhou | reading |
+----+------------+----------+---------+

单单使用take find这些是查询不出teacherinfo的信息的

Go 复制代码
	var t Teacher
	db.Take(&t)
	fmt.Println(t)

[4.938ms] [rows:-] SELECT count(*) FROM INFORMATION_SCHEMA.table_constraints WHERE constraint_schema = 'test' AND table_name = 'teacherinfo' AND co
nstraint_name = 'fk_teacher_teacher_info'
{1 yanzi 28 false {0 0  }}

想要查询用户详情使用preload

Go 复制代码
	var t Teacher
	db.Debug().Preload("TeacherInfo").Take(&t)
	fmt.Println(t)

[1.226ms] [rows:1] SELECT * FROM `teacherinfo` WHERE `teacherinfo`.`teacher_id` = 1
[41.415ms] [rows:1] SELECT * FROM `teacher` LIMIT 1                            
{1 yanzi 28 false {1 1 hangzhou video}}  

删除

Go 复制代码
	var t Teacher
	db.Take(&t, 2)
	db.Debug().Select("TeacherInfo").Delete(&t)

[3.472ms] [rows:1] DELETE FROM `teacherinfo` WHERE `teacherinfo`.`teacher_id` = 2
[60.613ms] [rows:1] DELETE FROM `teacher` WHERE `teacher`.`id` = 2   
相关推荐
明月看潮生1 小时前
青少年编程与数学 02-003 Go语言网络编程 09课题、Cookie
青少年编程·golang·网络编程·编程与数学
明月看潮生2 小时前
青少年编程与数学 02-003 Go语言网络编程 15课题、Go语言URL编程
开发语言·网络·青少年编程·golang·编程与数学
明月看潮生2 小时前
青少年编程与数学 02-003 Go语言网络编程 14课题、Go语言Udp编程
青少年编程·golang·网络编程·编程与数学
hlsd#3 小时前
go 集成go-redis 缓存操作
redis·缓存·golang
qq_1728055916 小时前
GIN 反向代理功能
后端·golang·go
__AtYou__17 小时前
Golang | Leetcode Golang题解之第535题TinyURL的加密与解密
leetcode·golang·题解
kevin_tech1 天前
Go API 多种响应的规范化处理和简化策略
开发语言·后端·golang·状态模式
幺零九零零1 天前
【Golang】sql.Null* 类型使用(处理空值和零值)
数据库·sql·golang
cookies_s_s1 天前
Golang--DOS命令、变量、基本数据类型、标识符
golang
__AtYou__1 天前
Golang | Leetcode Golang题解之第541题反转字符串II
leetcode·golang·题解