当前位置:网站首页>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
边栏推荐
- Dependency injection 2 advantage lifecycle
- [STM32 + esp-12s connect Tencent cloud IOT development platform 1] creation of cloud platform and burning of at firmware
- 生鲜行业数字化采购管理系统:助力生鲜企业解决采购难题,全程线上化采购执行
- 【leetcode】day1
- 0-1 knapsack problem
- Arbre binaire équilibré [Arbre AVL] - Insérer et supprimer
- USB (XVII) 2022-04-15
- One of the anti climbing methods
- Solution of intelligent supply chain collaboration platform in electronic equipment industry: solve inefficiency and enable digital upgrading of industry
- Oracle string sorting
猜你喜欢

2022注册测绘师备考开始 还在不知所措?手把手教你怎么考?

城联优品作为新力量初注入,相关上市公司股价应声上涨150%

B_ QuRT_ User_ Guide(38)

高效的S2B2C电商系统,是这样帮助电子材料企业提升应变能力的

How to change the formula picture in the paper directly into the formula in word

MySQL Architecture

Design and implementation of spark offline development framework

SRM supplier cloud collaborative management platform solution for building materials industry to realize business application scalability and configuration
![[compilation principle] lexical analysis design and Implementation](/img/8c/a3a50e6b029c49caf0d791f7d4513a.png)
[compilation principle] lexical analysis design and Implementation

Pycharm essential plug-in, change the background (self use, continuous update) | CSDN creation punch in
随机推荐
How to change the formula picture in the paper directly into the formula in word
【LeetCode】20、有效的括号
Dependency injection 2 advantage lifecycle
Oracle statistics by time
SAP HR labor contract information 0016
电子设备行业智能供应链协同平台解决方案:解决低效, 赋能产业数字化升级
Anxin vb01 offline voice module access intelligent curtain guidance
8.31 Tencent interview
通达信买基金安全吗?
Summary of SQL single table query 2020.7.27
Understand TCP's three handshakes and four waves with love
平衡二叉樹【AVL樹】——插入、删除
Take you hand in hand to build Eureka client with idea
B_ QuRT_ User_ Guide(37)
2022 Season 6 perfect children's model Shaanxi finals came to a successful conclusion
Fibonacci number of dynamic programming
2022 certified surveyors are still at a loss when preparing for the exam? Teach you how to take the exam hand in hand?
KeePass realizes automatic input of web pages
Idea automatically generates serialVersionUID
The efficient s2b2c e-commerce system helps electronic material enterprises improve their adaptability in this way