当前位置:网站首页>Gorm---- Association query
Gorm---- Association query
2022-06-25 13:28:00 【Favorite truffle chocolate】
GORM Relational query
1. Defined a User and Company, User Can contain more than one Company, as follows :
type User struct {
// here grom Yes map to table
ID int `gorm:"TYPE:int(11);NOT NULL;PRIMARY_KEY;INDEX"`
Name string `gorm:"TYPE: VARCHAR(255); DEFAULT:'';INDEX"`
Companies []Company `gorm:"FOREIGNKEY:UserId;ASSOCIATION_FOREIGNKEY:ID"`
CreatedAt time.Time `gorm:"TYPE:DATETIME"`
UpdatedAt time.Time `gorm:"TYPE:DATETIME"`
DeletedAt *time.Time `gorm:"TYPE:DATETIME;DEFAULT:NULL"`
}
type Company struct {
gorm.Model
Industry int `gorm:"TYPE:INT(11);DEFAULT:0"`
Name string `gorm:"TYPE:VARCHAR(255);DEFAULT:'';INDEX"`
Job string `gorm:"TYPE:VARCHAR(255);DEFAULT:''"`
UserId int `gorm:"TYPE:int(11);NOT NULL;INDEX"`
}
In the query User I hope that Company The information of , There are three ways :
Related
Use Related Method , You need to put User Good inquiry , And then according to User Specified in the definition FOREIGNKEY Go find Company, If there's no definition , You need to specify , as follows :
var u User
db.First(&u)
db.Model(&u).Related(&u.Companies).Find(&u.Companies)
User List traverses the list and queries one by one Company
Association
Use Association Method , You need to put User Good inquiry , And then according to User Specified in the definition AssociationForeignKey Go find Company, Must define , as follows :
var u User
db.First(&u)
db.Model(&u).Association("Companies").Find(&u.Companies)
Preload
Use Preload Method , In the query User Go and get Company The record of , as follows :
// Check the list user
var u User
db.Debug().Preload("Companies").First(&u)
// Corresponding sql sentence
// SELECT * FROM users LIMIT 1;
// SELECT * FROM companies WHERE user_id IN (1);
// Query all user
var list []User
db.Debug().Preload("Companies").Find(&list)
// Corresponding sql sentence
// SELECT * FROM users;
// SELECT * FROM companies WHERE user_id IN (1,2,3...);
2. Many to many :
Such as articles and labels
type Label struct {
ID uint `gorm:"primary_key" json:"id"` // label id
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"updated_at"`
Name string `json:"name" form:"name" gorm:"not null;"` // Tag name
Articles []Article `json:"articles" form:"articles" gorm:"many2many:article_label;" ` // Associated with the article
}
there Articles and Labels Respectively represents the table name
type Article struct {
ID uint `gorm:"primary_key" json:"id"` // article id
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"updated_at"`
//DeletedAt *time.Time `json:"-"`
UserId int `json:"user_id" form:"user_id" gorm:"not null;"` // Users
UserName string `json:"user_name" form:"user_name" gorm:"not null"` // Name of the user
Title string `json:"title" form:"title" gorm:"not null"` // Article title
Content string `json:"content" form:"content" gorm:"not null"` // Article content
ClassId int `json:"class_id" form:"class_id" gorm:"not null;"` // Classification
Recommend int `json:"recommend" form:"recommend" gorm:"not null"` // Is it recommended 1 recommend 2 Not recommended
Abstract string `json:"abstract" form:"abstract" gorm:"not null"` // Article summary
Audit string `json:"audit" form:"audit" gorm:"not null"` // Article review status 1 For adoption 2 To be reviewed 3 For not passing
Labels []Label `json:"labels" form:"labels" gorm:"many2many:article_label"` // Articles are associated with tags
}
// Articles approved according to the reverse association of labels , What we get here this Is to get the article
func (this *Label) LabArt() error {
return NewConn().Table(this.TableName()).
Preload("Articles", "audit = ?", "1").
Where("id = ?", this.ID).First(this).Error
}
If you think this article is good , Give a little sponsorship .

边栏推荐
- leetcode:剑指 Offer II 091. 粉刷房子【二维dp】
- QT mouse tracking
- 关于数据在内存中的存储下
- Prototype and prototype chain - constructor and instanceof
- Rust,程序员创业的最佳选择?
- OpenStack学习笔记-Glance组件深入了解
- leetcode:918. 环形子数组的最大和【逆向思维 + 最大子数组和】
- Method for wrapping multiple promise instances into a new promise instance
- Django framework - caching, signaling, cross site request forgery, cross domain issues, cookie session token
- 初始c语言时的一些知识
猜你喜欢

Golang keyboard input statement scanln scanf code example

关于一个图书小系统的实现

The priority of catch() and then (..., ERR) of promise

How to determine if a web worker has been created or closed

關於一道教材題的講解

[pit avoidance refers to "difficult"] antd cascader implements new customized functions

Confusion caused by the ramp

Configuring pytorch in win10 environment

Introduction to mongodb chapter 01 introduction to mongodb

Sword finger offer II 028 Flatten multi-level bidirectional linked list
随机推荐
Leetcode: Sword finger offer II 091 Painting house [2D DP]
OpenStack-----Nova源码分析之创建虚拟机
Solution to Nacos' failure to modify the configuration file mysql8.0
Analyse de l'optimisation de la réécriture des requêtes lazyagg de l'entrepôt
leetcode:剑指 Offer II 091. 粉刷房子【二维dp】
Cesium--- figure loading
学习编程的起点。
Golang keyboard input statement scanln scanf code example
Detailed explanation of string operation functions and memory functions
Explication d'un problème de manuel
Sword finger offer 04 Find in 2D array
ByteDance dev better technology salon is coming! Participate in the activity to win a good gift, and sign up for free within a limited time!
Used in time filter (EL table)
KVM script management - the road to dream
About data storage in memory
15 basic SEO skills to improve ranking
Maui's learning path (II) -- setting
揭秘GaussDB(for Redis):全面对比Codis
Regular match the phone number and replace the fourth to seventh digits of the phone number with****
[pit avoidance means "difficult"] the antd form dynamic form is deleted, and the first line is displayed by default