GORM 简单使用 | 青训营笔记

133 阅读2分钟

这是我参与「第三届青训营 -后端场」笔记创作活动的的第4篇笔记

GORM 安装

首先使用 go get -u github.com/jinzhu/gorm 下载 再在项目中导入:

import (
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

GORM 模型

给结构体中的变量设置对应的字段名: gorm:字段名。 例如:

type User struct {
    ID        uint           `gorm:"id;primaryKey"`
    Username  time.Time      `gorm:"username"`
    Password  time.Time      `gorm:"password"`
}

GORM 允许用标签控制字段级别的权限。这样您就可以让一个字段的权限是只读、只写、只创建、只更新或者被忽略。例如 User 的 ID 不可以写入数据库中,只允许从数据库中读。那么可以将 ID 设置为gorm:"->"。以下为官方给出的标签:

type User struct {
  Name string `gorm:"<-:create"` // allow read and create
  Name string `gorm:"<-:update"` // allow read and update
  Name string `gorm:"<-"`        // allow read and write (create and update)
  Name string `gorm:"<-:false"`  // allow read, disable write permission
  Name string `gorm:"->"`        // readonly (disable write permission unless it configured)
  Name string `gorm:"->;<-:create"` // allow read and create
  Name string `gorm:"->:false;<-:create"` // createonly (disabled read from db)
  Name string `gorm:"-"`            // ignore this field when write and read with struct
  Name string `gorm:"-:all"`        // ignore this field when write, read and migrate with struct
  Name string `gorm:"-:migration"`  // ignore this field when migrate with struct
}

GORM 创建

GORM 支持传入结构体进行创建。例如:

user := User{ID: 100, Username: "张三", Password: "123456"}
result := db.Create(&user)

除了单个插入,GORM 也支持多条数据插入,只需要将 user 改为数组即可。

此外,还有一种情况,根据不重复的字段进行查找,如果存在,则更新指定字段,如果不存在,则创建。例如:

db.Clauses(clause.OnConflict{
	Columns:   []clause.Column{{Name: "id"}},
	DoUpdates: clause.AssignmentColumns([]string{"password"}),
}).Create(user)

GORM 查询

GORM 查询有 FindFirstLast 三中方法。Fisrt 只返回一条记录;Last 只返回最后一条记录;Find 返回所有的记录。

如果结果要输出到结构体中,也可以使用 Scan 输出到结构体中。

当我们需要筛选条件的时候,我们可以通过 Where 来写筛选条件。使用方法和原生 MYSQL 类似。给 Where 传入筛选条件或者结构体即可。

除了 Where 之外,还有 JoinSelectOrderLimitOffsetCountGroupHaving 等 MySQL 中的操作。

SQL 预编译技术

除了提供基础的数据库操作之外,GORM 也采用了 SQL 预编译技术防御 SQL 注入。使用预编译,而后注入的参数将不会再进行SQL编译。也就是说其后注入进来的参数系统将不会认为它会是一条SQL语句,而默认其是一个参数,参数中的or或者and 等就不是SQL语法保留字了。