gorm 一对多联动创建

我愚蠢的认为在一对多关系中,被包含的那部分也要创建,答应我不要和我一样蠢了好嘛

gorm原生批量倒入
for _, city := range citys {
			sql:="REPLACE INTO `virus_data` (`Name`,`Todayconfirm`,`Confirm`,`Heal`,`Dead`) VALUES"
			for k,result:=range citys{
				//db.Where(model.VirusData{Name:result.Name}).First(&CheckCity)
				//if CheckCity.Name!=result.Name{
				if len(citys)-1==k{
					sql+=fmt.Sprintf("('%s','%s','%s','%s','%s');",result.Name,result.Todayconfirm,result.Confirm,result.Heal,result.Dead)
				}else {
					sql+=fmt.Sprintf("('%s','%s','%s','%s','%s'),",result.Name,result.Todayconfirm,result.Confirm,result.Heal,result.Dead)
				}
				}
	db.Exec(sql)
	结果成功批量导入,但外键是null
}
for _, city := range citys {
		virusdata := model.VirusData{
			Name:         city.Name,
			Todayconfirm: city.Todayconfirm,
			Confirm:      city.Confirm,
			Heal:         city.Heal,
			Dead:         city.Dead,
		}
		db.Where(model.VirusData{Name: virusdata.Name}).First(&beingTity)
		if beingTity.Name != "" {
		db.Model(&beingTity).Update(virusdata)
		} else {
			db.Create(&virusdata)
		}
		结果for循环io问题导致数据不全
func GiveValue(data model.VirusData,citys []model.VirusData)model.ProvinceData{
	provinceData:=model.ProvinceData{
		ProvinceName:  data.Name,
		Todayconfirm:  data.Todayconfirm,
		Confirm:       data.Confirm,
		Heal:          data.Heal,
		Dead:          data.Dead,
		ProvinceVirus: citys,
	}
	return provinceData
}
//将省和外国国家数据保存到数据库
func SaveProvince(Province model.VirusData,db *gorm.DB,citys []model.VirusData){
	var beingProvince model.ProvinceData
	var city []model.VirusData
	bigProvinceData:=GiveValue(Province,citys)
	////查询数据
	db.Where(model.ProvinceData{ProvinceName:bigProvinceData.ProvinceName}).First(&beingProvince)
	//	////没有就创建
	if beingProvince.ProvinceName!=Province.Name{
		db.Create(&bigProvinceData)
	}else {
	
		db.Where(model.VirusData{ProvinceDataID:beingProvince.Id}).Delete(&city)
		//gorm创建主表会将外键也一并创建了,但删除更新主表,外键表不会跟着删除更新
		db.Model(&beingProvince).Update(bigProvinceData)
	}
}

其实gorm的一对多:明确主表与从表的创建关系就很简单,从表的创建依附于主表但更新和删除没有联动关系,所以更新这块感觉作者大大有待升级

你可能感兴趣的:(gorm 一对多联动创建)