登录
首页 >  Golang >  Go问答

GORM是否支持一对多关系的单向插入?

来源:stackoverflow

时间:2024-03-24 21:42:39 239浏览 收藏

GORM 中一对多关系的单向插入是否可行引发疑问。本文探讨了这个问题,展示了当使用非约定主键时,需要明确指定关联外键才能实现单向插入。本文提供了代码示例来说明如何在 GORM 中正确设置一对多关系的单向插入。

问题内容

我有两个具有 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 不支持这样的插入?


解决方案


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

以上就是《GORM是否支持一对多关系的单向插入?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>