GORM是否支持单次插入并与多个项目有关联?
我有两个结构,它们有许多关系,如下所示:GORM是否支持单次插入并与多个项目有关联?,go,go-gorm,Go,Go Gorm,我有两个结构,它们有许多关系,如下所示: 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;"` Sta
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;"`
}
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对象,我正在尝试保存它,如下所示:
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;"`
}
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
),因此您需要提及
在代码中,它看起来像:
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"`
}