Golang Gorm フックの作成

作成するとき、データを挿入する前に何かを行う必要があります。フック関数は比較的単純で、作成前に実装するメソッドです。

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] |
+----+-------+------+-------------------+

おすすめ

転載: blog.csdn.net/qq_34556414/article/details/132889228