【问题标题】:Does GORM support single insert with has many relationship?GORM 支持单次插入有很多关系吗?
【发布时间】:2019-10-23 20:52:16
【问题描述】:

我有两个具有 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;"`
}

我有一个包含多个子作业的 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 不支持这样的插入?

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    由于您使用 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"`
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-26
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 2019-06-15
      • 2019-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多