Goweb---Gorm操作数据库(二)

Gorm允许用户自己自定义钩子操作,使用这些钩子操作,可以在增删改查操作前进行相关的操作和检验,它会在创建、更新、查询、删除时自动被调用。如果任何回调返回错误,GORM 将停止后续的操作并回滚事务。

自定义钩子函数
go 复制代码
package main

import (
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type User struct {
	ID       int    `gorm:"column:id"`
	Name     string `gorm:"column:name"`
	Age      int    `gorm:"column:age"`
	Birthday string `gorm:"column:birthday"`
}

func (u *User) BeforeCreate(tx *gorm.DB) error {
	
	fmt.Println("BeforeCreate user : ", u.Name)
	return nil
}
func main() {

	dsn := "root:828924@tcp(127.0.0.1:3306)/user?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("连接数据库失败:", err)
	}

	db.AutoMigrate(&User{})

	user := User{
		Name:     "张三",
		Age:      20,
		Birthday: "2000-01-01",
	}
	db.Create(&user)
}

func (u *User) BeforeCreate(tx *gorm.DB) error {

fmt.Println("BeforeCreate user : ", u.Name)

return nil

}

这是自定义的钩子函数,在用户执行db.Create(&user)前会执行BeforeCreate函数

其他相关操作都可以类推或者看相关文档

下面是Gorm的官方文档:
https://gorm.io/zh_CN/docs/create.html

跳过钩子函数:

可以通过使用SkipHooks会话模式跳过钩子函数

具体操作:

将db.Create(&user) 改为 db.Session(&gorm.Session{SkipHooks: true}).Create(&user)

在操作前将不会调用钩子函数。

相关推荐
倔强的石头10628 分钟前
openGauss数据库:从CentOS 7.9部署到实战验证
linux·数据库·centos
4***14902 小时前
MySQL调试技巧与工具
数据库·mysql
Arva .2 小时前
如何监控并优化慢 SQL?
数据库·sql
n***54383 小时前
【MySQL】MySQL内置函数--日期函数字符串函数数学函数其他相关函数
android·mysql·adb
linchare4 小时前
linux debian上只装mysql的客户端步骤
linux·mysql·debian
w***4245 小时前
【MySQL】复合查询
数据库·mysql
q***01776 小时前
【MySQL】表的基本操作
数据库·mysql·oracle
budingxiaomoli6 小时前
存储过程和触发器
数据库
q***12536 小时前
PostgreSQL_安装部署
数据库·postgresql
q***48256 小时前
mysql用户名怎么看
数据库·mysql