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   
相关推荐
007php0077 小时前
GoZero 上传文件File到阿里云 OSS 报错及优化方案
服务器·开发语言·数据库·python·阿里云·架构·golang
高 朗8 小时前
【GO基础学习】基础语法(2)切片slice
开发语言·学习·golang·slice
IT书架9 小时前
golang面试题
开发语言·后端·golang
醒过来摸鱼15 小时前
【Golang】协程
开发语言·后端·golang
灼华十一17 小时前
算法编程题-排序
数据结构·算法·golang·排序算法
宋发元17 小时前
Go语言使用 kafka-go 消费 Kafka 消息教程
golang·kafka·linq
宋发元18 小时前
Go消费kafka中kafkaReader.FetchMessage(ctx)和kafkaReader.ReadMessage(ctx)的区别
golang·kafka·linq
祁许1 天前
【Golang】手搓DES加密
开发语言·golang·密码学
凡人的AI工具箱1 天前
15分钟学 Go 实战项目六 :统计分析工具项目(30000字完整例子)
开发语言·数据库·人工智能·后端·golang
王大锤43911 天前
golang通用后台管理系统10(退出登录,注销token)
golang