当前位置:网站首页>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
边栏推荐
- B_QuRT_User_Guide(40)
- [experiment sharing] log in to Cisco devices through the console port
- Dataguard 主备清理归档设置
- List. How to achieve ascending and descending sort() 2020.8.6
- 0-1 knapsack problem
- Live server usage
- C method question 2
- 建筑建材行业SRM供应商云协同管理平台解决方案,实现业务应用可扩展可配置
- Boost regex library source code compilation
- postgis学习
猜你喜欢
生鲜行业数字化采购管理系统:助力生鲜企业解决采购难题,全程线上化采购执行
Anxin can internally test offline voice module vb-01 to communicate with esp-c3-12f
C simple question one
[compilation principle] lexical analysis design and Implementation
建筑建材行业SRM供应商云协同管理平台解决方案,实现业务应用可扩展可配置
As a new force, chenglian premium products was initially injected, and the shares of relevant listed companies rose 150% in response
B_QuRT_User_Guide(36)
Right click the idea file to create new. There is no solution to create new servlet
SAP HR labor contract information 0016
SAP HR奖罚信息导出
随机推荐
Balanced binary tree [AVL tree] - insert, delete
Design and implementation of spark offline development framework
企业应用需求导向开发之人力部门,员工考勤记录和实发工资业务程序案例
C simple question one
SQL database execution problems
Get started with mongodb
【7.5】15. 三数之和
Solution of intelligent supply chain collaboration platform in electronic equipment industry: solve inefficiency and enable digital upgrading of industry
Flash encryption process and implementation of esp32
Deep understanding of MySQL lock and transaction isolation level
As a new force, chenglian premium products was initially injected, and the shares of relevant listed companies rose 150% in response
0-1 knapsack problem
【7.4】25. K 个一组翻转链表
[STM32 + esp-12s connect Tencent cloud IOT development platform 1] creation of cloud platform and burning of at firmware
平衡二叉樹【AVL樹】——插入、删除
高效的S2B2C电商系统,是这样帮助电子材料企业提升应变能力的
激光slam学习(2D/3D、偏实践)
Markdown
Possible SQL for Oracle table lookup information
POJ2392 SpaceElevator [DP]