gpt4 book ai didi

Gorm Associations BeforeCreate 回调未按预期工作

转载 作者:行者123 更新时间:2023-12-01 22:24:58 25 4
gpt4 key购买 nike

我有 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()
}

地址结构

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
}

模型结构

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
}

我收到一个错误:错误 1364:字段“id”没有地址对象的默认值

但是,如果我删除 Address 关联,一切正常。并生成客户的 Id

    customer := & model.Customer{
Email: "a",
//Addresses: []model.Address{
//{
//Address1: "abc street",
//},
//},
}

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

最佳答案

您可以使用 scope.SetColumnBeforeCreate Hook 中设置字段的值

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

关于Gorm Associations BeforeCreate 回调未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60561188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com