This document combines the 9 chapters from the original GORM basics series into one continuous reference. Code examples, tables, and links are preserved from the source.
01 Traditional SQL CRUD
In MySQL, you need to know how to create and delete databases and tables.
You also need to know the commands for inserting, querying, deleting, and updating records.
Even without an ORM, you can connect to and operate a database directly.
Installing MySQL
I will not cover MySQL installation again here.
You can use the Xiaopi panel or Docker.
You can watch this video:
https://www.bilibili.com/video/BV1hu411T7TQ?p=2&vd_source=d26aaf9cd661f32d35974fafdac0de5b
One point to emphasize is that MySQL uses a client-server model, with a MySQL client and MySQL server.
You can connect to the database with the mysql command in the terminal because the MySQL client is installed.
Navicat, JDBC, and database-connection libraries in programming languages all count as clients.
Database Operations
# 查询全部的数据库
show databases;
# 创建数据库 并指定字符集和排序方式
create database gorm_new_db
character set utf8mb4
collate utf8mb4_unicode_ci;
# 选中数据库
use gorm_new_db;
# 删除数据库
drop database gorm_new_db;
Table operations
# 查询当前库的所有表
show tables;
# 建表
create table users
(
id bigint unsigned auto_increment primary key,
name varchar(50) not null default '',
age int unsigned not null default 0,
email varchar(100) not null default '',
created_at datetime default current_timestamp,
updated_at datetime default current_timestamp on update current_timestamp
) engine = innodb
default charset = utf8mb4
collate = utf8mb4_unicode_ci;
# 插入数据
insert into users (name, age, email)
values ('张三', 18, 'zhangsan@example.com'),
('李四', 20, 'lisi@example.com');
# 查询数据
select * from users;
# 删除数据
delete from users where id = 1;
# 更新数据
update users set name = '张三丰', age = 38 where id = 2;
# 删除表
drop table users;
02 Use SQL through Go
Install the driver.
go get -u github.com/go-sql-driver/mysql
Connect
db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/gorm_new_db")
if err != nil {
log.Fatalf("数据库连接失败 %s", err)
}
Execute SQL
Use the Exec function for operations other than queries.
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
)
func main() {
// 连接数据库
db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/gorm_new_db")
if err != nil {
log.Fatalf("数据库连接失败 %s", err)
}
defer db.Close()
_, err2 := db.Exec("CREATE TABLE users1(id INT NOT NULL , name VARCHAR(20), PRIMARY KEY(ID));")
if err2 != nil {
log.Fatal(err2)
}
fmt.Println("successfully create table")
}
Query SQL
Use the Query function.
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
)
func main() {
// 连接数据库
db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/gorm_new_db")
if err != nil {
log.Fatalf("数据库连接失败 %s", err)
}
defer db.Close()
res, err := db.Query("select id, name from users")
for res.Next() {
var id int
var name string
// 这里scan的字段要对上
err = res.Scan(&id, &name)
fmt.Println(id, name, err)
}
}
You can also use QueryRow to retrieve one row.
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
)
func main() {
// 连接数据库
db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/gorm_new_db")
if err != nil {
log.Fatalf("数据库连接失败 %s", err)
}
defer db.Close()
var id int
var name string
// 这里scan的字段要对上
err = db.QueryRow("select id, name from users").Scan(&id, &name)
fmt.Println(id, name, err)
}
03 Introducing GORM
GORM is introduced to make database operations easier.
When querying with native SQL,
the biggest issue is that results cannot be mapped easily to structs.
Database records resemble structs: a database column corresponds to a field.
Mapping databases to structs is therefore one of an ORM's key characteristics.
All ORMs work this way.
Use a class or struct to represent a table,
and an instance to represent one record.
Fields represent columns.
With that relationship in mind, let's look at GORM.
Installation
go get -u gorm.io/gorm
go get gorm.io/driver/mysql
The version in the video is v1.25.12
If your result differs while following the video and your code matches mine, check that the versions also match.
Connect GORM to a Database
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func main() {
// 连接数据库
db, err := gorm.Open(mysql.Open("root:root@tcp(127.0.0.1:3306)/gorm_new_db?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{})
fmt.Println(db, err)
}
Query Records
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type User struct {
ID uint
Name string
}
func main() {
// 连接数据库
db, err := gorm.Open(mysql.Open("root:root@tcp(127.0.0.1:3306)/gorm_new_db?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{})
if err != nil {
fmt.Println(err)
return
}
var userList []User
db.Find(&userList)
fmt.Println(userList)
}
GORM makes SQL operations very convenient.
04 Single-table Models and Operations
Table Structure
In GORM, a struct represents a table.
For example, the User table.
Usually, we use the Model suffix to indicate that a struct represents a table.
type UserModel struct {
ID int64 `gorm:"primaryKey"` // 主键
Name string `gorm:"not null;unique"` // 不能为空,且唯一
CreatedAt time.Time // 在创建记录时自动设置为当前时间
}
See field tags for tag references.
Automatically Generate a Table
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"time"
)
type UserModel struct {
ID int64 `gorm:"primaryKey"` // 主键
Name string `gorm:"not null;unique"` // 不能为空,且唯一
CreatedAt time.Time // 在创建记录时自动设置为当前时间。
}
func main() {
// 连接数据库
db, err := gorm.Open(mysql.Open("root:root@tcp(127.0.0.1:3306)/gorm_new_db?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{})
if err != nil {
fmt.Println(err)
return
}
err = db.AutoMigrate(&UserModel{})
if err != nil {
fmt.Println(err)
return
}
fmt.Println("生成表结构成功!")
}
Generating a table structure only adds fields; it does not delete or update existing fields.
Single-table Operations
These include create, read, update, and delete operations.
Insert Data
// InsertData 插入数据
func InsertData() {
user := UserModel{Name: "张三"}
err := DB.Create(&user).Error
// 创建成功之后,数据会回填
fmt.Println(user, err)
}
Batch insert
// InsertData 插入数据
func InsertData() {
var users = []UserModel{
{
Name: "王五",
},
{
Name: "李四",
},
}
err := DB.Create(&users).Error
fmt.Println(users, err)
}
Note:
Createaccepts a pointer to a struct or a slice.
Hooks for inserted data
type UserModel struct {
ID int64 `gorm:"primaryKey"` // 主键
Name string `gorm:"not null;unique"` // 不能为空,且唯一
CreatedAt time.Time // 在创建记录时自动设置为当前时间。
}
func (u *UserModel) BeforeCreate(tx *gorm.DB) error {
fmt.Println("创建的钩子函数")
u.Name = "枫枫"
return nil
}
If an insert hook returns an error, the data is not inserted.
Query Data
// 查全部
var users []UserModel
DB.Find(&users)
fmt.Println(users)
// 带条件查询
users = []UserModel{}
DB.Find(&users, "name = ?", "张三")
fmt.Println(users)
// 获取一条记录
var user UserModel
DB.Take(&user)
fmt.Println(user)
// 如果查不到则会报错
user = UserModel{}
err := DB.Take(&user, "id = ?", 100).Error
if err == gorm.ErrRecordNotFound {
fmt.Println("不存在的记录")
}
// 如果不想出现错误
user = UserModel{}
err = DB.Limit(1).Find(&user, "id = ?", 100).Error
fmt.Println(err)
// 打印实际的sql
DB.Debug().Take(&user, "id = ?", 1)
Update
There are several methods: Save, Update, UpdateColumn, and Updates.
They differ as follows:
Saveupdates a record when a primary key is present and can update zero values; otherwise it creates a record.Updatecan update zero values and requires a condition.UpdateColumncan update zero values and does not run update hooks.Updatesupdates nonzero fields when given a struct; a map can update zero values.
save
// 创建
var user = UserModel{
Name: "枫枫1",
}
DB.Save(&user)
fmt.Println(user)
// 更新
user = UserModel{
ID: 9,
Name: "枫枫2",
CreatedAt: time.Now(),
}
DB.Save(&user)
fmt.Println(user)
Update hook
func (u *UserModel) BeforeUpdate(tx *gorm.DB) (err error) {
fmt.Println("更新的钩子函数")
return nil
}
Update and UpdateColumn
DB.Model(&UserModel{}).
Where("id = ?", 1).
Update("name", "张三") // 走了更新钩子
DB.Model(&UserModel{}).
Where("id = ?", 1).
UpdateColumn("name", "张三")
Updates
var user = UserModel{ID: 1}
DB.Model(&user).Updates(UserModel{
Name: "张三丰",
})
user = UserModel{ID: 2}
// 不会更新零值
DB.Model(&user).Updates(UserModel{
Name: "",
})
user = UserModel{ID: 2}
// 会更新零值
DB.Model(&user).Updates(map[string]any{
"name": "",
})
Expr
This is commonly used to reference the original value of a field.
For example, increment an age by one.
DB.Model(&UserModel{}).
Where("id = ?", 1).
UpdateColumn("age", gorm.Expr("age + 1"))
Delete
var user = UserModel{ID: 10}
DB.Delete(&user)
DB.Delete(&UserModel{}, 9)
// 批量删除
DB.Delete(&UserModel{}, []int{1, 2, 3})
Hook function
func (u *UserModel) BeforeDelete(tx *gorm.DB) (err error) {
fmt.Println("删除钩子")
return
}
Soft Delete
If a model contains a gorm.DeletedAt field, which is also included in gorm.Model, it automatically gains soft-delete support.
When Delete is called, GORM does not remove the record from the database. It sets DeletedAt to the current time, and ordinary queries no longer return the record.
Find deleted records
DB.Unscoped().Find(&users)
Delete permanently
db.Unscoped().Delete(&user)
05 Advanced Single-table Queries
Where query
Write conditions directly
var user UserModel
DB.Where("id = 5").Take(&user)
fmt.Println(user)
user = UserModel{}
DB.Where("id = 5 or age = 11").Take(&user)
fmt.Println(user)
Pay attention to the order of where, and then in front of the & function
Structure conditions
- Non-empty field query
var user = UserModel{ID: 5, Name: "李四"}
DB.Debug().Where(user).Take(&user)
// SELECT * FROM `user_models` WHERE (`user_models`.`id` = 5 AND `user_models`.`name` = '李四') AND `user_models`.`id` = 5IMIT 1
fmt.Println(user)
take, first, and last will only check the primary key
Map condition
- You can check empty fields
var user UserModel
DB.Debug().Where(map[string]any{
"age": 0,
}).Take(&user)
// SELECT * FROM `user_models` WHERE `age` = 0 LIMIT 1
fmt.Println(user)
Nested where conditions
query := DB.Where("age = ? and name = ?", 11, "王五1")
var user UserModel
DB.Debug().Where(query).Take(&user)
// SELECT * FROM `user_models` WHERE (age = 11 and name = '王五1') LIMIT 1
fmt.Println(user)
Or
or query
var user UserModel
DB.Debug().Or("name = ?", "王五").Or("age = 12").Take(&user)
// SELECT * FROM `user_models` WHERE (name = '王五' OR age = 12) LIMIT 1
fmt.Println(user)
Not
non-query
var user UserModel
DB.Debug().Not("age = 12").Take(&user)
// SELECT * FROM `user_models` WHERE NOT age = 12 LIMIT 1
fmt.Println(user)
Sort
var userList []UserModel
// 降序
DB.Order("age desc").Find(&userList)
fmt.Println(userList)
// 升序
DB.Order("age asc").Find(&userList)
fmt.Println(userList)
Scan
Only specific fields are required
var nameList []string
DB.Model(UserModel{}).Select("name").Scan(&nameList)
fmt.Println(nameList)
Or you can use Pluck directly
var nameList []string
DB.Model(UserModel{}).Pluck("name", &nameList)
fmt.Println(nameList)
You can create a new structure with fewer fields
type User struct {
Name string
ID int64
}
var users []User
DB.Model(UserModel{}).Scan(&users)
fmt.Println(users)
// 字段如果不对应
type Options struct {
Label string `gorm:"column:name"`
Value int64 `gorm:"column:id"`
}
var options []Options
DB.Model(UserModel{}).Scan(&options)
fmt.Println(options)
After grouping, data from specific fields is required
type User struct {
Age int
Count int
}
var us []User
DB.Model(UserModel{}).Group("age").Select("age, count(*) as count").Scan(&us)
fmt.Println(us)
Remove duplicates
var nameList []string
DB.Model(UserModel{}).Distinct("name").Select("name").Scan(&nameList)
fmt.Println(nameList)
Pagination query
var users []UserModel
// 第一页
DB.Limit(10).Offset(0).Find(&users)
fmt.Println(users)
// 第二页
DB.Limit(10).Offset(10).Find(&users)
fmt.Println(users)
// 第三页
DB.Limit(10).Offset(20).Find(&users)
fmt.Println(users)
// 第n页
Scope
Many times, we often use repeated query methods
Then you can extract these methods that may be reused
func Age18(tx *gorm.DB) *gorm.DB {
return tx.Where("age >= ?", 18)
}
var users []UserModel
DB.Scopes(Age18).Find(&users)
fmt.Println(users)
You can also use the characteristics of higher-order functions to implement scopes with parameters.
func NameIn(nameList ...string) func(tx *gorm.DB) *gorm.DB {
return func(tx *gorm.DB) *gorm.DB {
return tx.Where("name in ?", nameList)
}
}
var users []UserModel
DB.Scopes(NameIn("王五", "李四")).Find(&users)
fmt.Println(users)
Query hook
func (u *UserModel) AfterFind(tx *gorm.DB) (err error) {
fmt.Println("查询钩子")
return
}
Native SQL
Use Row to perform query operations
var users []UserModel
DB.Raw("select * from user_models where name = ?", "王五").Scan(&users)
fmt.Println(users)
Use Exec to manipulate data
DB.Exec("update user_models set name = ? where id = ?", "张三", 4)
06 gorm new-multi-table relationship
When learning mysql multi-table relationships
We all know that there are one-to-one relationships, one-to-many relationships, and many-to-many relationships.
We don’t understand it according to gorm’s BelongsTo and Has Many
But to understand it from the actual scene
One-to-one relationship
There is an obvious one-to-one relationship between users and user details.
So how do we express this one-to-one relationship?
In mysql, you need to add a field to another table
For example, user table and user_detail table
Then you need to add a user_id field to the user_detail table
Or add a new user_detail_id field in the user table
We call this field a foreign key field
In a one-to-one relationship, the foreign key field can be in any table
How to express it in gorm?
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var DB *gorm.DB
type UserModel struct {
ID int64
Name string `gorm:"size:32"`
Age int
}
type UserDetailModel struct {
ID int64
UserID int64
UserModel UserModel `gorm:"foreignKey:UserID"`
Email string `gorm:"size:64"`
}
func init() {
db, err := gorm.Open(mysql.Open("root:root@tcp(127.0.0.1:3306)/gorm_new_db?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{})
if err != nil {
fmt.Println(err)
return
}
DB = db
}
func migrate() {
err := DB.AutoMigrate(&UserModel{}, &UserDetailModel{})
if err != nil {
fmt.Println(err)
return
}
fmt.Println("表结构生成成功")
}
func main() {
migrate()
}
This method will generate entity foreign keys. If it is for personal use, it would be better to have foreign keys, which can do some data constraints.
If you do not need to generate entity foreign keys, you can configure the following
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true, // 不生成实体外键
})
So for this table structure
UserDetailModel in UserModel is a back reference
UserModel in UserDetailModel is a forward reference
type UserModel struct {
ID int64
Name string `gorm:"size:32"`
Age int
UserDetailModel *UserDetailModel `gorm:"foreignKey:UserID"`
}
type UserDetailModel struct {
ID int64
UserID int64
UserModel UserModel `gorm:"foreignKey:UserID"`
Email string `gorm:"size:64"`
}
So how to add, delete, modify and check?
Insert data
Insert user first, then insert user_detail
DB.Create(&UserModel{
Name: "枫枫",
UserDetailModel: &UserDetailModel{
Email: "xxx@qq.com",
},
})
Insert user_detail into existing user
DB.Create(&UserDetailModel{
UserID: 2,
Email: "zzz@qq.com",
})
Know user, insert user_detail
var user UserModel
DB.Take(&user, 2)
DB.Create(&UserDetailModel{
UserModel: user,
Email: "zzz@qq.com",
})
Query data
// 根据用户查用户详情
var user UserModel
DB.Preload("UserDetailModel").Take(&user, 2)
fmt.Println(user.Name, user.UserDetailModel.Email)
// 根据用户详情查用户
var userDetail UserDetailModel
DB.Preload("UserModel").Take(&userDetail, "user_id = ?", 2)
fmt.Println(userDetail.Email, userDetail.UserModel.Name)
The focus is Preload preloading
Delete data
For deletion under multi-table relationships
The situation is different
Generally involves deletion of associations
For example, users and user details. If the user is deleted, then there is no need to keep the user details and cascading deletion is required.
var user UserModel
DB.Take(&user, 2)
DB.Select("UserDetailModel").Delete(&user)
However, there are still some that do not require cascading deletion, and the corresponding foreign keys need to be set to Null.
var user UserModel
DB.Take(&user, 1)
DB.Delete(&user)
DB.Model(&user).Association("UserDetailModel").Clear()
Both of these situations are very common association deletions and can be implemented in a simpler way.
type UserModel struct {
ID int64
Name string `gorm:"size:32"`
Age int
UserDetailModel *UserDetailModel `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE"` // CASCADE 或者 SET NULL
}
The prerequisite is that entity foreign keys must be generated, and after modifying the relationship, the entity foreign keys must be deleted and generated again.
One-to-many relationship (dog-licking and goddess version)
There are more one-to-many in life
Users and articles
Licking dog and goddess
Classes and students
type Girl struct {
ID int64
Name string `gorm:"size:32"`
BoyList []Boy `gorm:"foreignKey:GirlID"`
}
type Boy struct {
ID int64
GirlID int64
Name string `gorm:"size:32"`
Girl Girl `gorm:"foreignKey:GirlID"`
}
So for Girl, the Body is what she owns, which is called Has Many.
For Boy, Girl is where he belongs, called Belongs To
So how to do one-to-many addition, deletion, modification and query?
Insert data
Create a goddess with several licking dogs
DB.Create(&Girl{
Name: "娜娜",
BoyList: []Boy{
{Name: "张三"},
{Name: "王五"},
},
})
Create a boy and bring your own goddess
DB.Create(&Boy{
Name: "枫枫",
Girl: Girl{
Name: "露露",
},
})
Create a Boy and associate it with an existing goddess
var girl Girl
DB.Take(&girl, "name = ?", "露露")
DB.Create(&Boy{
Name: "李四",
Girl: girl,
})
Related query
Check the goddess, and also find out his licking dog
var girl Girl
DB.Preload("BoyList").Take(&girl, "name = ?", "露露")
fmt.Println(girl)
Conditional Preload
girl = Girl{}
DB.Preload("BoyList", "name = ?", "枫枫").Take(&girl, "name = ?", "露露")
fmt.Println(girl)
Check the goddess’s dog licking list
girl = Girl{}
DB.Take(&girl, "name = ?", "露露")
var bodyList []Boy
DB.Model(girl).Association("BoyList").Find(&bodyList)
fmt.Println(bodyList)
Check the total number of licking dogs of the goddess
count := DB.Model(girl).Association("BoyList").Count()
fmt.Println(count)
Association operations
No. 1 and No. 2 stopped licking and replaced them with No. 3.
var b3 = Boy{
ID: 3,
}
girl := Girl{}
DB.Take(&girl, "name = ?", "露露")
DB.Model(&girl).Association("BoyList").Replace([]Boy{b3})
No more licking
girl := Girl{}
DB.Take(&girl, "name = ?", "露露")
DB.Model(&girl).Association("BoyList").Clear()
Numbers 1 and 3 started licking again
girl := Girl{}
DB.Take(&girl, "name = ?", "露露")
DB.Model(&girl).Association("BoyList").Append([]Boy{{ID: 1}, {ID: 3}})
Only No. 3 quit
girl := Girl{}
DB.Take(&girl, "name = ?", "露露")
DB.Model(&girl).Association("BoyList").Delete([]Boy{{ID: 3}})
Many-to-many relationship
There are more many-to-many relationships in life
Articles and tags
books and authors
Licking dog and goddess
Many-to-many relationships must be related with the help of a third table
Such as articles and tags
| id | article_id | tag_id |
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
It is easy to see that article 1 has two tags, 1 and 2, and article 2 has a tag 1.
So how to implement it in gorm?
type Article struct {
ID int64
Title string `gorm:"size:32"`
TagList []Tag `gorm:"many2many:article_tags;"`
}
type Tag struct {
ID int64
Title int64 `gorm:"size:32"`
ArticleList []Article `gorm:"many2many:article_tags;"`
}
Insert data
Create an article and create tags
article := Article{Title: "文章1", TagList: []Tag{
{Title: "go"},
{Title: "python"},
}}
DB.Create(&article)
Create an article and select an existing tag
tagIDList := []int64{1, 2}
var tagList []Tag
DB.Find(&tagList, "id in ?", tagIDList)
DB.Create(&Article{
Title: "文章2",
TagList: tagList,
})
Related query
Check the article list and bring out the tags
var articleList []Article
DB.Preload("TagList").Find(&articleList)
fmt.Println(articleList)
Association operations
Update a post's tag list
var article Article
DB.Take(&article, "title = ?", "文章1")
DB.Model(&article).Association("TagList").Replace([]Tag{
{ID: 1},
{Title: "后端"},
})
Customize the third table
Take users’ collection of articles as an example
It is the many-to-many relationship between users and articles.
If the default third table is used and the user wants to know when a certain article was collected, there is no way.
table structure
type UserModel struct {
ID int64
Name string
CollArticleList []ArticleModel `gorm:"many2many:user2_article_models;joinForeignKey:UserID;JoinReferences:ArticleID"`
}
type ArticleModel struct {
ID int64
Title string `gorm:"size:32"`
}
type User2ArticleModel struct {
UserID int64 `gorm:"primaryKey"`
UserModel UserModel `gorm:"foreignKey:UserID"`
ArticleID int64 `gorm:"primaryKey"`
ArticleModel ArticleModel `gorm:"foreignKey:ArticleID"`
CreatedAt time.Time `json:"createdAt"`
}
The key point is many2many: the name of the generated table must match the name of the third table
Then joinForeignKey corresponds to the ID of this table. For example, the joinForeignKey of the user table is UserID.
JoinReferences corresponds to the ID of the other party's table, and the JoinReferences of the user table is ArticleID.
Then you need to add SetupJoinTable, otherwise the creation hook of the third table will not be used.
// 必须要加这个才会走第三张表的创建钩子
DB.SetupJoinTable(&UserModel{}, "CollArticleList", &User2ArticleModel{})
Then creation and deletion will be the same as before.
DB.Create(&UserModel{
Name: "张三",
CollArticleList: []ArticleModel{
{Title: "文章1"},
{Title: "文章2"},
},
})
var user UserModel
DB.Take(&user)
DB.Select("CollArticleList").Delete(&user)
Query
Query cannot use Preload directly, because the Preload output is the other party's table, and there is no collection time.
So the normal operation is to directly check the third table
type UserCollArticleResponse struct {
Name string
UserID int64
ArticleTitle string
ArticleID int64
Date time.Time
}
var userID = 4
var userArticleList []models.User2ArticleModel
var collList []UserCollArticleResponse
global.DB.Preload("UserModel").Preload("ArticleModel").Find(&userArticleList, "user_id = ?", userID)
for _, model := range userArticleList {
collList = append(collList, UserCollArticleResponse{
Name: model.UserModel.Name,
UserID: model.UserID,
ArticleTitle: model.ArticleModel.Title,
ArticleID: model.ArticleID,
Date: model.CreatedAt,
})
}
fmt.Println(collList)
07 gorm new-custom data type
In many cases, we have the need to store json
Then you need to use the custom data type in gorm
Custom data types must implement the Scanner and Valuer interfaces
To put it simply, it is converted into an ordinary string for storage when it is stored in the database. When querying, it is mapped to a structure.
JSON custom data type
json data is more commonly used
type Info struct {
Like []string `json:"like"`
Addr string `json:"addr"`
Age int `json:"age"`
}
// Scan 实现 sql.Scanner 接口,Scan 将 value 扫描至 Jsonb
func (j *Info) Scan(value interface{}) error {
bytes, ok := value.([]byte)
if !ok {
return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
}
result := Info{}
err := json.Unmarshal(bytes, &result)
*j = result
return err
}
// Value 实现 driver.Valuer 接口,Value 返回 json value
func (j Info) Value() (driver.Value, error) {
return json.Marshal(j)
}
Note: Don’t be smart here and change the pointer method or receiver method. Scan is a pointer method and Value is a receiver method.
Insert data
type User struct {
ID int64
Name string `gorm:"size:32"`
Info Info `gorm:"type:longtext" json:"info"`
}
DB.Create(&User{
Name: "枫枫",
Info: Info{
Age: 21,
Addr: "湖南长沙",
Like: []string{"唱", "跳", "rap"},
},
})
Query data
var user User
DB.Take(&user, 1)
fmt.Println(user.Name, user.Info.Like)
Serialization
If you just store json data, you can use gorm's serialization and bring your own json
type User struct {
ID int64
Name string `gorm:"size:32"`
Info Info `gorm:"type:longtext;serializer:json" json:"info"`
}
Of course, you can also customize the serializer, please refer to the following:
https://gorm.io/zh_CN/docs/serializer.html
Enumeration type
In some cases, it is necessary to store some identification status content in the database.
For example, describing the log level, there are usually a few fixed values, such as info, warning, and error.
If you store strings directly, it is obviously a waste of space.
So you can use custom types
type Status int8
const (
Running Status = 1
Warning Status = 2
)
func (s Status) MarshalJSON() (data []byte, err error) {
var str string
switch s {
case Running:
str = "运行中"
case Warning:
str = "警告"
}
return json.Marshal(str)
}
type User struct {
ID int64
Name string `gorm:"size:32"`
Status Status `json:"status"`
}
Because when returning to the front end, it will definitely be json serialized, so when it is returned to the front end, it will be the corresponding Chinese.
However, we can also optimize it further. Returning only Chinese characters is too little. We also need to return the numbers themselves. How to do this?
func (s Status) MarshalJSON() (data []byte, err error) {
var str string
switch s {
case Running:
str = "运行中"
case Warning:
str = "警告"
}
return json.Marshal(map[string]any{
"status": int8(s),
"statusTitle": str,
})
}
08 gorm new-transaction
A transaction is a series of database operations defined by the user. These operations can be regarded as a completed unit of logical processing work. Either all of them are executed or none of them are executed. They are indivisible units of work.
A very vivid example, Zhang San transfers 100 yuan to Li Si. In the program, Zhang San's balance will be -100, and Li Si's balance will be +100. The whole event is a whole. If any step is wrong, the entire event will fail.
Gorm transactions are enabled by default. To ensure data consistency, GORM performs write operations (create, update, delete) within transactions.
If there is no requirement for this, you can disable it on initialization, which will give you about a 30%+ performance improvement.
Generally not recommended to disable
// 全局禁用
db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{
SkipDefaultTransaction: true,
})
Ordinary affairs
Take Zhang San's transfer of money to Li Si as an example. The consequences of not using transactions
var zhangsan, lisi User
DB.Take(&zhangsan, "name = ?", "张三")
DB.Take(&lisi, "name = ?", "李四")
// 张三给李四转账100元
// 先给张三-100
zhangsan.Money -= 100
DB.Model(&zhangsan).Update("money", zhangsan.Money)
// 模拟失败的情况
// 再给李四+100
lisi.Money += 100
DB.Model(&lisi).Update("money", lisi.Money)
In the case of failure, either Zhang San lost 100 yuan in vain, or Li Si got 100 yuan out of thin air.
This is obviously illogical and illegal
So, what does it look like to use transactions?
var zhangsan, lisi User
DB.Take(&zhangsan, "name = ?", "张三")
DB.Take(&lisi, "name = ?", "李四")
// 张三给李四转账100元
DB.Transaction(func(tx *gorm.DB) error {
// 先给张三-100
zhangsan.Money -= 100
err := tx.Model(&zhangsan).Update("money", zhangsan.Money).Error
if err != nil {
fmt.Println(err)
return err
}
// 再给李四+100
lisi.Money += 100
err = tx.Model(&lisi).Update("money", lisi.Money).Error
if err != nil {
fmt.Println(err)
return err
}
// 提交事务
return nil
})
After using transactions, they become one, succeed together and fail together.
Manual transactions
// 开始事务
tx := db.Begin()
// 在事务中执行一些 db 操作(从这里开始,您应该使用 'tx' 而不是 'db')
tx.Create(...)
// ...
// 遇到错误时回滚事务
tx.Rollback()
// 否则,提交事务
tx.Commit()
The code just now can also be implemented like this
var zhangsan, lisi User
DB.Take(&zhangsan, "name = ?", "张三")
DB.Take(&lisi, "name = ?", "李四")
// 张三给李四转账100元
tx := DB.Begin()
// 先给张三-100
zhangsan.Money -= 100
err := tx.Model(&zhangsan).Update("money", zhangsan.Money).Error
if err != nil {
tx.Rollback()
}
// 再给李四+100
lisi.Money += 100
err = tx.Model(&lisi).Update("money", lisi.Money).Error
if err != nil {
tx.Rollback()
}
// 提交事务
tx.Commit()
09 gorm new-gorm configuration
This course does not cover a lot of gorm configuration at the beginning.
That's because as much as possible, the convention is greater than the configuration.
If you write code according to gorm's convention, you can save a lot of configuration items.
Use ID as primary key
By default, the field named ID will be used as the primary key of the table
You can also set other fields as primary keys through the tag primaryKey
Plural table name
GORM uses Snake Name of the structure name as the table name. For the structure User, according to the convention, its table name is users
If you do not want to use plural table names, you can modify it in the configuration
db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
TablePrefix: "t_", // 表名前缀
SingularTable: true, // 使用单数表名
NoLowerCase: true, // 关闭蛇形命名
NameReplacer: strings.NewReplacer("CID", "Cid"), // use name replacer to change struct/field name before convert it to db name
},
})
You can also use the TableName function to customize the table name
func (User) TableName() string {
return "profiles"
}
Snake column name
Use gorm:"column:name" for custom column names
Special time field
CreatedAt
For models with the CreatedAt field, when creating a record, if the field value is zero, the value of the field is set to the current time
UpdatedAt
For models with the UpdatedAt field, when updating a record, set the value of this field to the current time. When creating a record, if the field value is zero, the value of the field is set to the current time
DeletedAt
soft delete