GORM 是否支持单次插入有很多关系?

Does GORM support single insert with has many relationship?

我有两个具有 HasMany 关系的结构,如下所示:

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;"`
}

我有一个包含多个 Subjob 的 MasterJob 对象,我正在尝试如下所示保存它:

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
}

当我尝试保存此对象时,仅保存了 MasterJob 数据。我是不是做错了,或者 GORM 不支持这样插入?

由于您使用 MasterJobID 作为主键而不是遵循 gorm 中的约定 (ID),因此您需要提及 Association ForeignKey

在代码中它看起来像:

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"`
}