Golang基础:青训营第五节课|青训营笔记

92 阅读4分钟

这是我参与「第三届青训营 -后端场」笔记创作活动的的第3篇笔记。 首先在此推荐一篇写的很好的笔记,方便自己和他人查看学习

juejin.cn/post/709789… 文章里面将sql/database基础讲的很好,看完后能对Grom和sql/database有个大概的了解,课堂上的相关代码也能够看懂90%了。

我这边对课堂PPT总体做一个记录。

本节课的课程目录

Snipaste_2022-05-16_20-38-42.png

设计原理

Snipaste_2022-05-16_20-44-31.png

GROM基础知识使用

GROM原理

仅做了解即可

在其中介绍了CONNPool插件

本次由于PPT代码太过于模糊,因此并未粘贴PPT代码,此处准备几段方便理解的代码


代码为对GROM的举例运用,来源于**# GORM 使用入门** laravelacademy.org/post/22057

package main

import (

"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"time"

)

type Post struct {

Id int
Title string
Content string
Author string `sql:"not null"`
CreatedAt time.Time
Comments []Comment

}

type Comment struct {

Id int
Content string
Author string `sql:"not null"`
PostId int `sql:"index"`
CreatedAt time.Time

}

var DbConn *gorm.DB

func init() {

var err error
DbConn, err = gorm.Open("mysql", "root:root@/test_db?charset=utf8mb4&parseTime=true")
if err != nil {
    panic(err)
}
DbConn.AutoMigrate(&Post{}, &Comment{})

}

func main() {

post := Post{Title: "GORM 示例教程", Content: "基于 GORM 进行数据库增删改查", Author: "学院君"}

// 通过 GORM 插入文章记录
DbConn.Create(&post)
fmt.Println(post)

// 通过关联关系新增评论并将其附加到对应的文章记录
comment := Comment{Content: "Test Comment", Author: "学院君小号"}
DbConn.Model(&post).Association("Comments").Append(comment)

// 查询文章记录
var gormPost Post
DbConn.Where("author = ?", "学院君").First(&gormPost)

// 查询包含评论数据的文章记录
var comments []Comment
DbConn.Model(&gormPost).Related(&comments)
fmt.Println(comments[0])

}`

数据库连接

由于 GORM 也实现了 database/sql 接口,所以建立数据库连接和之前使用 go-sql-driver/mysql 包类似,只是调用方法改成了 gorm.Open

1

DbConn, err = gorm.Open("mysql", "root:root@/test_db?charset=utf8mb4&parseTime=true")

参数和之前完全一样,引入的驱动包调整为 jinzhu/gorm 即可:

1

"github.com/jinzhu/gorm"

_ "github.com/jinzhu/gorm/dialects/mysql"

注:更多关于 GORM 数据库连接配置的细节,请参考 GORM 官方文档

数据表自动迁移

和使用 go-sql-driver/mysql 包不同的是,这次我们不再需要手动创建数据表,因为 GORM 提供了数据表自动迁移功能:

1

DbConn.AutoMigrate(&Post{}, &Comment{})

通过 AutoMigrate 方法传入要迁移的模型类实例即可,GORM 会自动创建对应的数据表,表名规则是模型类名小写的复数形式。

模型类定义

接下来,我们看下模型类的定义: type Post struct {

Id int
Title string
Content string
Author string `sql:"not null"`
CreatedAt time.Time
Comments []Comment

}

type Comment struct {

Id int
Content string
Author string `sql:"not null"`
PostId int `sql:"index"`
CreatedAt time.Time

} 这里定义了两个模型类,Post 和 Comment,分别对应数据表 posts 和 comments,并且在 Post 中通过如下方式定义了 Post 和 Comment 之间的一对多关联:

1

Comments []Comment

这里我们没有用结构体标签指定关联外键(GORM 支持通过结构体标签设置数据表字段属性),GORM 底层会自动维护这个关联,默认规则是在 Comment 中的 PostId 字段(即当前模型类名加上主键 ID 后缀)。

但是还是有一些字段设置了结构体标签,这是为了给该字段添加额外的数据表字段约束,比如索引、是否允许为空等:

1

Author string sql:"not null"


2

PostId int `sql:"index"`


> 注:更多模型类定义的细节和结构体标签设置,请参考 [GORM 官方文档](https://gorm.io/zh_CN/docs/models.html)。

#### 增删改查

我们继续来看增删改查和关联模型的操作,在 GORM 中,我们总算不用维护 SQL 语句了,所有的增删改查操作都可以通过 GORM 库提供的方法来实现,比如要创建一条记录可以这么做:


1

post := Post{Title: "GORM 示例教程", Content: "基于 GORM 进行数据库增删改查", Author: "学院君"}


2

DbConn.Create(&post)


模型类中的 `Id` 和 `CreatedAt` 字段系统会自动维护,不需要显示设置。

> 注:如果要实现修改、删除和查询操作,请参考 [GORM 官方文档 CRUD 接口部分](https://gorm.io/zh_CN/docs/),这些也都有相应的内置方法。

#### 关联查询

如果要在上述模型实例上创建与之关联的评论,可以这么做:


1

comment := Comment{Content: "Test Comment", Author: "学院君小号"}


2

DbConn.Model(&post).Association("Comments").Append(comment)


最后要查询包含关联评论记录的主题,可以这么做:


1

var gormPost Post


2

DbConn.Where("author = ?", "学院君").First(&gormPost)


3


4

var comments []Comment


5

DbConn.Model(&gormPost).Related(&comments)