当前位置:网站首页>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 .

边栏推荐
- 初始c语言的知识2.0
- Openstack learning notes -nova component insight
- Serenvlt first met
- NR-ARFCN和信道栅格、同步栅格和GSCN
- Drago Education - typescript learning
- Cesium model Daquan glb/glft format
- Simple realization of mine sweeping
- [pit avoidance refers to "difficult"] halfcheckedkeys rendering problem in semi selected status of antd tree
- Explanation of a textbook question
- C # switch between Chinese and English input methods
猜你喜欢

It's an artifact to launch a website in a few minutes

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

The starting point for learning programming.

关于一道教材题的讲解

J2EE from entry to earth 01 MySQL installation

Maui的学习之路(二)--设置

Introduction to mongodb chapter 01 introduction to mongodb

Uncover gaussdb (for redis): comprehensive comparison of CODIS

. NET in China - What's New in . NET

[pit avoidance means "difficult"] the antd form dynamic form is deleted, and the first line is displayed by default
随机推荐
关于一个图书小系统的实现
SSH secret free function for # scripting
Explication d'un problème de manuel
Configuring pytorch in win10 environment
Heavyweight live | bizdevops: the way to break the technology situation under the tide of digital transformation
Unity 2D游戏中的抛物运动
[flask tutorial] flask development foundation and introduction
Pointer, it has to say that the subject
About data storage in memory
论文阅读:Graph Contrastive Learning with Augmentations
Detailed explanation of string operation functions and memory functions
leetcode:456. 132 模式【单调栈】
Openstack learning notes (II)
Related examples of data storage in memory
Three lines of code to simply modify the project code of the jar package
Nova组件源码分析之冷迁移与Resize
Of binary tree_ Huffman tree_ Huffman encoding
OpenStack学习笔记(二)
Uncover gaussdb (for redis): comprehensive comparison of CODIS
Rust,程序員創業的最佳選擇?