gpt4 book ai didi

go - GORM是否支持单插有很多关系?

转载 作者:行者123 更新时间:2023-12-01 22:17:35 27 4
gpt4 key购买 nike

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

我有一个具有多个Subjobs的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"`
}

关于go - GORM是否支持单插有很多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58520756/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com