当前位置:网站首页>gorm 关联关系小结
gorm 关联关系小结
2022-07-07 21:53:00 【咳咳,您好请多指教!】
数据库设计
表1:
CREATE TABLE `blog_user` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(50) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
`created_at` datetime(3) DEFAULT NULL,
`updated_at` datetime(3) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_blog_user_created_at` (`created_at`),
KEY `idx_blog_user_updated_at` (`updated_at`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
--------------------------------------------------------------------------------------------------------------------
表2:
CREATE TABLE `blog_article` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
`user_id` bigint unsigned NOT NULL,
`is_hot` tinyint NOT NULL,
`created_at` datetime(3) DEFAULT NULL,
`updated_at` datetime(3) DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
1.Belongs To 属于
用户与文章的关系 文章表存在用户表的id 作为 外键 ,文章 属于 用户
1-1 User 的 Model 结构体
type User struct {
models.BaseModel
UserName string `gorm:"column:username;" json:"username"`
Password string `json:"-"`
models.CommonTimestampsField
}
1-2 Article 的 Model 结构体
type Article struct {
models.BaseModel
Title string `json:"title"`
IsHot int8 `json:"is_hot"`
UserId int64 `json:"user_id"` //外键
User users.User `json:"user" gorm:"ForeignKey:UserId"`//关联的对象
}
查询:
Joins 或 Preload 预加载
var results []Article
database.DB.Model(&Article{}).Joins("User").Find(&results).Error, results
2. hasOne 一对一
用户与文章的关系 文章表存在用户表的id 作为 外键 ,用户 与 文章 一对一 (假定 一个人只能有一片文章)
2-1 User 的 Model 结构体
type User struct {
models.BaseModel
UserName string `gorm:"column:username;" json:"username"`
Password string `json:"-"`
Article article.Article `gorm:"foreignKey:UserId"`//一对一关联
models.CommonTimestampsField
}
2-2 Article 的 Model 结构体
type Article struct {
models.BaseModel
Title string `json:"title"`
IsHot int8 `json:"is_hot"`
UserId int64 `json:"user_id"` //外键
}
查询:
Preload 预加载
var results []Article
database.DB.Model(&User{}).Preload("Article").Find(&results).Error, results
3.Has Many 一对多 用户与文章的关系 文章表存在用户表的id 作为 外键 ,用户 与 文章 一对多
3-1 User 的 Model 结构体
type User struct {
models.BaseModel
UserName string `gorm:"column:username;" json:"username"`
Password string `json:"-"`
Article []article.Article `gorm:"foreignKey:UserId"`
models.CommonTimestampsField
}
3-2 Article 的 Model 结构体
type Article struct {
models.BaseModel
Title string `json:"title"`
IsHot int8 `json:"is_hot"`
UserId int64 `json:"user_id"` //外键
}
查询:
Preload 预加载
var results []Article
database.DB.Model(&User{}).Preload("Article").Find(&results).Error, results
4.Many To Many
4-1.新增 是体表 language & blog_user_has_language
CREATE TABLE `blog_language` (
`id` int NOT NULL AUTO_INCREMENT,
`title` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
------------------------------------------------------------------------------------
CREATE TABLE `blog_user_has_language` (
`user_id` int NOT NULL DEFAULT '0',
`language_id` int NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
4-2.结构体
type User struct {
models.BaseModel
UserName string `gorm:"column:username;" json:"username"`
Password string `json:"-"`
Languages []language.Language `gorm:"many2many:user_has_language;"`
models.CommonTimestampsField
}
4-3.查询:
Preload 预加载
var results []Article
database.DB.Model(&User{}).Preload("Languages").Find(&results).Error, results
边栏推荐
- 包装行业智能供应链S2B2B商城解决方案:开辟电商消费新生态
- 企业应用需求导向开发之人力部门,员工考勤记录和实发工资业务程序案例
- [STM32 + esp-12s connect Tencent cloud IOT development platform 1] creation of cloud platform and burning of at firmware
- S2b2b mall solution of intelligent supply chain in packaging industry: opening up a new ecosystem of e-commerce consumption
- 8.31 Tencent interview
- Arbre binaire équilibré [Arbre AVL] - Insérer et supprimer
- B_QuRT_User_Guide(39)
- Oracle statistics by time
- How to change the formula picture in the paper directly into the formula in word
- redis缓存工具类,值得拥有~
猜你喜欢
As a new force, chenglian premium products was initially injected, and the shares of relevant listed companies rose 150% in response
SAP 内存参数调优过程
进度播报|广州地铁七号线全线29台盾构机全部完成始发
包装行业智能供应链S2B2B商城解决方案:开辟电商消费新生态
[stm32+esp8266 connect Tencent cloud IOT development platform 2] stm32+esp8266-01s connect Tencent cloud
USB (XV) 2022-04-14
二叉排序树【BST】——创建、查找、删除、输出
Class C design questions
SAP HR奖罚信息导出
Home appliance industry channel business collaboration system solution: help home appliance enterprises quickly realize the Internet of channels
随机推荐
SAP memory parameter tuning process
Extract the file name under the folder under win
[summary] some panels and videos seen
Mobile heterogeneous computing technology - GPU OpenCL programming (basic)
Three questions TDM
One week learning summary of STL Standard Template Library
Anxinco esp32-a1s development board is adapted to Baidu dueros routine to realize online voice function
Live server usage
[stm32+esp8266 connect Tencent cloud IOT development platform 2] stm32+esp8266-01s connect Tencent cloud
Balanced binary tree [AVL tree] - insert, delete
城联优品作为新力量初注入,相关上市公司股价应声上涨150%
FPGA basics catalog
Dataguard 主备清理归档设置
B / Qurt Utilisateur Guide (36)
C number of words, plus ¥, longest word, average value
C cat and dog
平衡二叉树【AVL树】——插入、删除
Summary of SQL single table query 2020.7.27
POJ2392 SpaceElevator [DP]
MySQL架构