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   
相关推荐
007php00715 小时前
Go语言zero项目部署后启动失败问题分析与解决
java·服务器·网络·python·golang·php·ai编程
MClink21 小时前
Go怎么做性能优化工具篇之pprof
开发语言·性能优化·golang
m0_748254661 天前
go官方日志库带色彩格式化
android·开发语言·golang
Algorithm15761 天前
云原生相关的 Go 语言工程师技术路线(含博客网址导航)
开发语言·云原生·golang
Narutolxy1 天前
深入探讨 Go 中的高级表单验证与翻译:Gin 与 Validator 的实践之道20241223
开发语言·golang·gin
Hello.Reader1 天前
全面解析 Golang Gin 框架
开发语言·golang·gin
hkNaruto2 天前
【P2P】【Go】采用go语言实现udp hole punching 打洞 传输速度测试 ping测试
golang·udp·p2p
入 梦皆星河2 天前
go中常用的处理json的库
golang
海绵波波1072 天前
Gin-vue-admin(2):项目初始化
vue.js·golang·gin
每天写点bug2 天前
【go每日一题】:并发任务调度器
开发语言·后端·golang