golang gorm 批量插入不同数据

func BatchUpdateForm(reportForms []model.ReportForm)  {
	ids := []int64{}
	formIdMap :=make(map[int64]map[string]interface{})
	for _,val :=range reportForms {
		formIdMap[val.ID]=webgo.StructToMap(val)
		ids=append(ids, val.ID)
	}
	var report model.ReportForm
	columnMap := webgo.GetStructTagJson(&report) //结构体的TAG转MAP
	vals := []interface{}{}
	sqlStr := "Update report_form Set "
	for key,val :=range columnMap {
		sqlStr+=val+" = CASE id"
		for _,rfval :=range reportForms{
			sqlStr+=" when "+ strconv.FormatInt(rfval.ID,10)+" THEN ?"
			vals=append(vals,formIdMap[rfval.ID][key])
		}
		sqlStr+=" END,"
	}
	sqlStr=beego.Substr(sqlStr,0, len(sqlStr)-1)
	sqlStr += " where id in (?)"
	vals=append(vals, ids)
	err := db.SqlDB.Exec(sqlStr, vals...).Error
	if err!=nil {
		panic(err)
	}
}

 

你可能感兴趣的:(golang)