Your Question

Hi! I am trying to insert in many2many associations, but it fails due to NOT NULL error, e.g.:

type Car struct {
    ID        uint      `gorm:"primary_key" json:"id"`
    CreatedAt time.Time `gorm:"index" json:"created_at"`
    UpdatedAt time.Time `gorm:"index" json:"updated_at"`
        Passengers []Passenger `gorm:"many2many:car_passengers"`
}

type Passenger struct {
    ID        uint      `gorm:"primary_key" json:"id"`
    CreatedAt time.Time `gorm:"index" json:"created_at"`
    UpdatedAt time.Time `gorm:"index" json:"updated_at"`
}

Obviously there are tables for cars & passagers, plus relation table of car_passengers containing:

id NOT NULL, PRIMARY, AI
car_id NOT NULL
passenger_id NOT NULL
created_at NOT NULL
updated_at NOT NULL

the problem I have - once I try to save with FullSaveAssociations: true, I get SQL error on car_passengers entry of having fields created_at & updated_at not nullable. Thus - how can I tell gorm to set these values?

The document you expected this should be explained

It should have been explained in associations https://gorm.io/docs/associations.html

Expected answer

I want to know how to set created_at & updated_at values so when saving it doesn't fail

Comment From: janisbiz

Figured it out. Closing.

Comment From: leorockspoon

How did you do this?

Comment From: supuwoerc

@jinzhu Any best practices on this issue please? 请问关于这个问题有什么最佳实践吗?