Golang Gorm Crear GANCHO

Al crear, desea hacer algo antes de insertar datos. La función de enlace es relativamente simple, es un método para implementar antes de crear.

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

Supongo que te gusta

Origin blog.csdn.net/qq_34556414/article/details/132889228
Recomendado
Clasificación