Gorm的新增

01 普通用法

DB.Create(&Struct): 注意是结构体的指针

package book

import (
	"fmt"
	"gin/settings"
	"github.com/gin-gonic/gin"
	"strconv"
)

var DB = settings.DdFunc()

func book(request *gin.Context) {
	DB.AutoMigrate(&Book{}) // 自动数据库迁移
	name := request.PostForm("name") // 从formdata中获取数据
	message := request.PostForm("message")
	price := request.PostForm("price")
	priceInt, err := strconv.ParseInt(price, 10, 32) //转化为int64
	if err != nil {
		request.JSON(200, "价格格式错误")
	}
	bookObj := Book{
		Name:    name,
		Price:   uint32(priceInt), // 转化为uint32
		Message: message,
	}
	result := DB.Create(&bookObj) // 创建数据操作返回结果,注意是指针
	rErr := result.Error // 如果创建成功,结果是nil
	if rErr != nil {
		request.JSON(200, "fail")
	}
	num := result.RowsAffected // 插入几条数据
	fmt.Println(num)
	request.JSON(200, "success")
}
  • 创建和上一条数据一样的数据,指定只更新的字段
package book

import (
	"fmt"
	"gin/settings"
	"github.com/gin-gonic/gin"
	"strconv"
)

var DB = settings.DdFunc()

func book(request *gin.Context) {
	DB.AutoMigrate(&Book{})
	name := request.PostForm("name")
	message := request.PostForm("message")
	price := request.PostForm("price")
	priceInt, err := strconv.ParseInt(price, 10, 32)
	if err != nil {
		request.JSON(200, "价格格式错误")
	}
	bookObj := Book{
		Name:    name,
		Price:   uint32(priceInt),
		Message: message,
	}
	//result := DB.Create(&bookObj)
	result := DB.Select("Name").Create(&bookObj) // Select中指定的字段会改变,其他字段和上一条数据一致
	rErr := result.Error
	if rErr != nil {
		request.JSON(200, "fail")
	}
	num := result.RowsAffected
	fmt.Println(num)
	request.JSON(200, "success")
}

注意:

Select参数空字符串时,创建和上一条完全一样的数据

  • 创建和上一条数据不同的字段的新数据
package book

import (
	"fmt"
	"gin/settings"
	"github.com/gin-gonic/gin"
	"strconv"
)

var DB = settings.DdFunc()

func book(request *gin.Context) {
	DB.AutoMigrate(&Book{})
	name := request.PostForm("name")
	message := request.PostForm("message")
	price := request.PostForm("price")
	priceInt, err := strconv.ParseInt(price, 10, 32)
	if err != nil {
		request.JSON(200, "价格格式错误")
	}
	bookObj := Book{
		Name:    name,
		Price:   uint32(priceInt),
		Message: message,
	}
	result := DB.Omit("price").Create(&bookObj) // Omit中指定的字段不发生改变,与上一条数据一样
	rErr := result.Error
	if rErr != nil {
		request.JSON(200, "fail")
	}
	num := result.RowsAffected
	fmt.Println(num)
	request.JSON(200, "success")
}

02 批量插入

03 钩子函数

在特定的情况下自动调用

gorm允许用户定义的钩子函数有四个

BeforeSave:在保存之前

BeforeCreate:Create方法之前

AfterSave:保存之后

AfterCreate:提交之后

package book

import "github.com/jinzhu/gorm"

func (book *Book) BeforeCreate(scope *gorm.Scope) error { // 定义该方法,自动会被调用
	scope.SetColumn("Id", 100)
	return nil
}
posted @ 2021-03-15 10:36  tianzhh_lynn  阅读(289)  评论(0编辑  收藏  举报