0
votes

I have two structs having HasMany relationship like shown below:

type MasterJob struct {
    MasterJobID int       `gorm:"column:master_job_id;not null;AUTO_INCREMENT"`
    StartedAt   time.Time `gorm:"column:started_at;not null"`
    CompletedAt time.Time `gorm:"column:completed_at;"`
    Status      Status    `gorm:"column:status;"`
    Subjobs     []Subjob  `gorm:"foreignkey:MasterJobID"`
}

type Subjob struct {
    SubjobID     int       `gorm:"type:serial;primary_key:yes;column:subjob_id;AUTO_INCREMENT"`
    StartedAt    time.Time `gorm:"column:started_at;not null"`
    CompletedAt  time.Time `gorm:"column:completed_at;DEFAULT:nil"`
    Status       Status    `gorm:"column:status;"`
    MasterJobID  int       `gorm:"column:master_job_id;"`
}

I have a MasterJob object with multiple Subjobs and I am trying to save it like shown below:

func (r *repo) CreateJob() (int, []error) {
    subJobs := make([]models.Subjob, 0)
    job := models.Subjob{
        Status:       models.StatusInprogress,
        StartedAt:    time.Now(),
        SurveyUUID:   uuid.New(),
        FlightlineID: 1,
    }
    subJobs = append(subJobs, job)
    masterJob := &models.MasterJob{
        Status:    models.StatusInprogress,
        StartedAt: time.Now(),
        Subjobs:   subJobs,
    }
    errors := r.DB.Create(masterJob).GetErrors()
    if len(errors) > 0 {
        fmt.Println(errors)
        return -1, errors
    }
    return masterJob.MasterJobID, nil
}

When I try to save this object, only MasterJob data is getting saved. Am I doing this wrong or Insert like this is not supported in GORM?

1

1 Answers

1
votes

Since you are using MasterJobID as your primary key instead of following the conventions in gorm (ID), you need to mention the Association ForeignKey

In code it will look like:

type MasterJob struct {
    MasterJobID int       `gorm:"column:master_job_id;not null;AUTO_INCREMENT"`
    StartedAt   time.Time `gorm:"column:started_at;not null"`
    CompletedAt time.Time `gorm:"column:completed_at;"`
    Status      Status    `gorm:"column:status;"`
    Subjobs     []Subjob  `gorm:"foreignkey:MasterJobID;association_foreignkey:MasterJobID"`
}