猿问

Gorm 关联 BeforeCreate 回调未按预期工作

我有Customer结构


type Customer struct {

    Model

    Email                 string     `json:"email,omitempty"`

    Addresses             []Address

}


func (c *Customer) BeforeCreate() (err error) {

    if err := c.GenerateID(); err != nil {

        return err

    }

    return c.Marshal()

}

和Address结构


type Address struct {

    Model

    CustomerID         string

    Address1           string

}


func (a *Address) BeforeCreate() error {

// The ID is still generated, but the insert query has no `id` in it

    if err := a.GenerateID(); err != nil {

        return err

    }

    return nil

}

Model结构


type Model struct {

    ID        string `gorm:"primary_key;type:varchar(100)"`

    CreatedAt time.Time

    UpdatedAt time.Time

    DeletedAt *time.Time `sql:"index"`

}


func (model *Model) GenerateID() error {

    uv4, err := uuid.NewV4()

    if err != nil {

        return err

    }

    model.ID = uv4.String()

    return nil

}

一个客户:


customer := &model.Customer{

    Email:     "a",

    Addresses: []model.Address{

        {

            Address1: "abc street",

        },

    },

}



if err := gormDb.Create(customer).Error; err != nil {

    return nil, err

}

I got an error: Error 1364: Field 'id' doesn't have a default value对于地址对象


但是,如果我删除这些Address关联,一切都会奏效。并Id生成客户。


    customer := & model.Customer{

    Email:     "a",

    //Addresses: []model.Address{

        //{

            //Address1: "abc street",

        //},

    //},

}

如何保持Address关联并成功插入,并且仍然使用这种 ID 生成机制?


青春有我
浏览 392回答 2
2回答

MYYA

您可以使用scope.SetColumn在BeforeCreate钩子中设置字段的值func (a *Address) BeforeCreate(scope *gorm.Scope) error {  scope.SetColumn("ID", uuid.New())  return nil}参考:https ://v1.gorm.io/docs/create.html#Setting-Field-Values-In-Hooks

幕布斯7119047

您应该使用tx.Statement.SetColumn在 GORM 挂钩中设置字段值,例如BeforeCreate. 以下是示例实现。func (s Product3) BeforeCreate(tx *gorm.DB) (err error) {    tx.Statement.SetColumn("Price", s.Price+100)    return nil}GORM Github repo 的参考实现链接 https://github.com/go-gorm/gorm/blob/ac722c16f90e0e0dffc600c7f69e791c110d788c/tests/hooks_test.go#L306-L309来自 GORM 文档的参考链接 https://gorm.io/docs/update.html#Change-Updating-Values
随时随地看视频慕课网APP

相关分类

Go
我要回答