Gorm BeforeCreate钩子无法生成UUID

nwo49xxi  于 2023-08-01  发布在  Go
关注(0)|答案(2)|浏览(141)

我尝试在每次创建公司时生成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')

olmpazwi

olmpazwi1#

看起来你正在使用gorm v1,我认为你需要gorm v2。导入为"gorm.io/gorm"
最低工作示例:

package main

import (
    "fmt"
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

type User struct {
    Id int
    Name string
}

func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
    u.Name = "Steve"
    return
}

func (u *User) BeforeSave(tx *gorm.DB) (err error) {
    u.Name = "Sally"
    return
}

func main() {
    db, err := gorm.Open(sqlite.Open("hooks.db"), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }
    db.AutoMigrate(&User{})
    user := User{
        Name: "Blake",
    }
    db.Create(&user)
    fmt.Println(user.Name)
    user.Name = "Tyler"
    db.Save(&user)
    fmt.Println(user.Name)
}

字符串
图纸:

Steve
Sally

zyfwsgd6

zyfwsgd62#

如果你在CompanyModel上定义了BeforeCreate钩子,你需要在Base模型上手动调用BeforeCreate钩子。
因此companyModel上的BeforeCreate钩子模型将是

func (c *CompanyModel) BeforeCreate(tx *gorm.DB) (err error) {
    // whatever you have here

    return c.Base.BeforeCreate(tx)
}

字符串

相关问题