Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gorm Associations BeforeCreate Callback not working as expected

Tags:

go

go-gorm

I have Customer struct

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

And Address struct

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 struct

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
}

A Customer:

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 for the Address object

But if I remove the Address associations, things work. And the customer's Id is generated.

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

How can I keep the Address associations and insert both successfully, and still using this ID-generation mechanism?

like image 652
Trần Xuân Huy Avatar asked Sep 17 '25 01:09

Trần Xuân Huy


1 Answers

You can use scope.SetColumn to set a field’s value in BeforeCreate hook

func (a *Address) BeforeCreate(scope *gorm.Scope) error {
  scope.SetColumn("ID", uuid.New())
  return nil
}

Ref: https://v1.gorm.io/docs/create.html#Setting-Field-Values-In-Hooks

like image 187
Eklavya Avatar answered Sep 18 '25 17:09

Eklavya