我尝试在每次创建公司时生成UUID。我想在hook函数中这样做,但它不起作用。我试图在程序执行时使其死机,但钩子没有响应。
我遵循了如何实现钩子的文档,但它不适合我。
挂钩文档:https://gorm.io/docs/hooks.html
import (
"time"
"github.com/jinzhu/gorm"
uuid "github.com/satori/go.uuid"
)
type Base struct {
ID uuid.UUID `gorm:"type:UUID;" json:"_id"`
CreatedAt time.Time `gorm:"type:Date;" json:"created_at"`
UpdatedAt time.Time `gorm:"type:Date;" json:"updated_at"`
DeletedAt *time.Time `gorm:"type:Date;" json:"deleted_at"`
}
type CompanyModel struct {
Base
// Departments []DepartmentModel `gorm:"foreignKey:id" json:"departments"`
Cvr int `gorm:"not null" json:"cvr"`
Name string `gorm:"not null" json:"name"`
}
// BeforeCreate creates
func (u *Base) BeforeCreate(tx *gorm.DB) (err error) {
u.ID = uuid.NewV4()
panic(u.ID)
return
}
// BeforeSave creates
func (u *Base) BeforeSave(tx *gorm.DB) (err error) {
u.ID = uuid.NewV4()
panic(u.ID)
return
}
字符串
我创建一个公司通过以下
tx := db.Session(&gorm.Session{SkipHooks: false}).Create(&models.CompanyModel{
Cvr: 12333,
Name: "test,
// Departments: company.Departments,
},
)
型
执行时保存的值总是:
[1.479ms] [rows:0] INSERT INTO "company_models" ("id","created_at","updated_at","deleted_at","cvr","name") VALUES ('00000000-0000-0000-0000-000000000000','2021-04-21 18:00:51.879','2021-04-21 18:00:51.879',NULL,12333,'test')
型
2条答案
按热度按时间olmpazwi1#
看起来你正在使用gorm v1,我认为你需要gorm v2。导入为
"gorm.io/gorm"
。最低工作示例:
字符串
图纸:
型
zyfwsgd62#
如果你在
CompanyModel
上定义了BeforeCreate
钩子,你需要在Base
模型上手动调用BeforeCreate
钩子。因此
companyModel
上的BeforeCreate
钩子模型将是字符串