Moonlit Torii

GORM Basics

MySQL, native SQL, GORM models, queries, relationships, custom types, transactions, and configuration.

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

sql
# 查询全部的数据库
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

sql
# 查询当前库的所有表
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
go get -u github.com/go-sql-driver/mysql

Connect

go
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.

go
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.

go
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.

go
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
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

go
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

go
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.

go
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

go
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

go
// InsertData 插入数据
func InsertData() {
  user := UserModel{Name: "张三"}
  err := DB.Create(&user).Error
  // 创建成功之后,数据会回填
  fmt.Println(user, err)
}

Batch insert

go
// InsertData 插入数据
func InsertData() {
  var users = []UserModel{
    {
      Name: "王五",
    },
    {
      Name: "李四",
    },
  }
  err := DB.Create(&users).Error
  fmt.Println(users, err)
}

Note: Create accepts a pointer to a struct or a slice.

Hooks for inserted data

go
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

go
// 查全部
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:

  1. Save updates a record when a primary key is present and can update zero values; otherwise it creates a record.
  2. Update can update zero values and requires a condition.
  3. UpdateColumn can update zero values and does not run update hooks.
  4. Updates updates nonzero fields when given a struct; a map can update zero values.

save

go
// 创建
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

go
func (u *UserModel) BeforeUpdate(tx *gorm.DB) (err error) {
  fmt.Println("更新的钩子函数")
  return nil
}

Update and UpdateColumn

go
DB.Model(&UserModel{}).
  Where("id = ?", 1).
  Update("name", "张三")  // 走了更新钩子

DB.Model(&UserModel{}).
  Where("id = ?", 1).
  UpdateColumn("name", "张三")

Updates

go
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.

go
DB.Model(&UserModel{}).
  Where("id = ?", 1).
  UpdateColumn("age", gorm.Expr("age + 1"))

Delete

go
var user = UserModel{ID: 10}
DB.Delete(&user)

DB.Delete(&UserModel{}, 9)

// 批量删除
DB.Delete(&UserModel{}, []int{1, 2, 3})

Hook function

go
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

typescript
DB.Unscoped().Find(&users)

Delete permanently

typescript
db.Unscoped().Delete(&user)

05 Advanced Single-table Queries

Where query

Write conditions directly

go
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

  1. Non-empty field query
go
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

  1. You can check empty fields
go
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

go
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

go
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

go
var user UserModel
DB.Debug().Not("age = 12").Take(&user)
//  SELECT * FROM `user_models` WHERE NOT age = 12 LIMIT 1
fmt.Println(user)

Sort

go
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

go
  var nameList []string
  DB.Model(UserModel{}).Select("name").Scan(&nameList)
  fmt.Println(nameList)

Or you can use Pluck directly

go
  var nameList []string
  DB.Model(UserModel{}).Pluck("name", &nameList)
  fmt.Println(nameList)

You can create a new structure with fewer fields

go
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

go
  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

go
  var nameList []string
  DB.Model(UserModel{}).Distinct("name").Select("name").Scan(&nameList)
  fmt.Println(nameList)

Pagination query

go
  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

go
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.

go
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

go
func (u *UserModel) AfterFind(tx *gorm.DB) (err error) {
  fmt.Println("查询钩子")
  return
}

Native SQL

Use Row to perform query operations

go
  var users []UserModel
  DB.Raw("select * from user_models where name = ?", "王五").Scan(&users)
  fmt.Println(users)

Use Exec to manipulate data

sql
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?

go
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

go
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

go
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

go
DB.Create(&UserModel{
  Name: "枫枫",
  UserDetailModel: &UserDetailModel{
    Email: "xxx@qq.com",
  },
})

Insert user_detail into existing user

go
DB.Create(&UserDetailModel{
  UserID: 2,
  Email:  "zzz@qq.com",
})

Know user, insert user_detail

go
var user UserModel
DB.Take(&user, 2)

DB.Create(&UserDetailModel{
  UserModel: user,
  Email:     "zzz@qq.com",
})

Query data

go
// 根据用户查用户详情
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.

go
  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.

go
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.

go
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

go
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

go
DB.Create(&Girl{
  Name: "娜娜",
  BoyList: []Boy{
    {Name: "张三"},
    {Name: "王五"},
  },
})

Create a boy and bring your own goddess

go
  DB.Create(&Boy{
    Name: "枫枫",
    Girl: Girl{
      Name: "露露",
    },
  })

Create a Boy and associate it with an existing goddess

go
var girl Girl
DB.Take(&girl, "name = ?", "露露")

DB.Create(&Boy{
  Name: "李四",
  Girl: girl,
})

Check the goddess, and also find out his licking dog

go
  var girl Girl
  DB.Preload("BoyList").Take(&girl, "name = ?", "露露")
  fmt.Println(girl)

Conditional Preload

go
  girl = Girl{}
  DB.Preload("BoyList", "name = ?", "枫枫").Take(&girl, "name = ?", "露露")
  fmt.Println(girl)

Check the goddess’s dog licking list

go
  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

go
  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.

go
var b3 = Boy{
  ID: 3,
}
girl := Girl{}
DB.Take(&girl, "name = ?", "露露")

DB.Model(&girl).Association("BoyList").Replace([]Boy{b3})

No more licking

go
  girl := Girl{}
  DB.Take(&girl, "name = ?", "露露")
  DB.Model(&girl).Association("BoyList").Clear()

Numbers 1 and 3 started licking again

go
  girl := Girl{}
  DB.Take(&girl, "name = ?", "露露")
  DB.Model(&girl).Association("BoyList").Append([]Boy{{ID: 1}, {ID: 3}})

Only No. 3 quit

go
  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

idarticle_idtag_id
111
212
321

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?

go
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

go
  article := Article{Title: "文章1", TagList: []Tag{
    {Title: "go"},
    {Title: "python"},
  }}
  DB.Create(&article)

Create an article and select an existing tag

go
  tagIDList := []int64{1, 2}
  var tagList []Tag
  DB.Find(&tagList, "id in ?", tagIDList)

  DB.Create(&Article{
    Title:   "文章2",
    TagList: tagList,
  })

Check the article list and bring out the tags

go
  var articleList []Article
  DB.Preload("TagList").Find(&articleList)
  fmt.Println(articleList)

Association operations

Update a post's tag list

go
  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

go
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.

go
 // 必须要加这个才会走第三张表的创建钩子
  DB.SetupJoinTable(&UserModel{}, "CollArticleList", &User2ArticleModel{})

Then creation and deletion will be the same as before.

go
DB.Create(&UserModel{
  Name: "张三",
  CollArticleList: []ArticleModel{
    {Title: "文章1"},
    {Title: "文章2"},
  },
})
go
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

go
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

go
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

go
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

go
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

go
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

go
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?

go
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

go
// 全局禁用
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

go
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?

go
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

go
// 开始事务
tx := db.Begin()

// 在事务中执行一些 db 操作(从这里开始,您应该使用 'tx' 而不是 'db')
tx.Create(...)

// ...

// 遇到错误时回滚事务
tx.Rollback()

// 否则,提交事务
tx.Commit()

The code just now can also be implemented like this

go
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

go
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

go
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