Golang Gorm 创建HOOK

创建的时候,在插入数据之前,想要做一些事情。钩子函数比较简单,就是实现before create的一个方法。

Golang Gorm 创建HOOK_第1张图片

package main

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

type Student struct {
	ID    int64
	Name  string `gorm:"size:6"`
	Age   int
	Email *string
}

func (*Student) TableName() string {
	return "student"
}

func (student *Student) BeforeCreate(tx *gorm.DB) error {
	email := "[email protected]"
	student.Email = &email
	//确定要添加的话就返回nil
	return nil
}

func main() {
	dsn := "root:7PXjAkY!&nlR@tcp(192.168.11.128:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
	db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	db.AutoMigrate(&Student{})


	db.Create(&Student{
		Name: "hh",
		Age:  1,
	})

}


mysql> select * from student;
+----+-------+------+-------------------+
| id | name  | age  | email             |
+----+-------+------+-------------------+
|  1 | lucas |   30 | NULL              |
|  3 | hh    |    1 | [email protected] |
+----+-------+------+-------------------+

你可能感兴趣的:(Golang,Gorm,golang)