创建的时候,在插入数据之前,想要做一些事情。钩子函数比较简单,就是实现before create的一个方法。
package mainimport ("gorm.io/driver/mysql""gorm.io/gorm"
)type Student struct {ID int64Name string `gorm:"size:6"`Age intEmail *string
}func (*Student) TableName() string {return "student"
}func (student *Student) BeforeCreate(tx *gorm.DB) error {email := "1239683670@qq.com"student.Email = &email//确定要添加的话就返回nilreturn 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 | 1239683670@qq.com |
+----+-------+------+-------------------+