简体   繁体   中英

Multiple update using GORM in Golang

I am trying to make APIs using GIN and GORM. Now i have stucked in one of the APIs. This API will create multiple entries in the DB. I have the json body like this. The size of array will vary.

{
 "key" : [1,2]
}

With this, I have some other parameter that i am getting from the url-

key1 := c.Param("value1")
key2 := c.Param("value2")

Now i want to create multiple entries [1,2] on DB with data of key1 and key2 like-

Key1 Key2 key
value1 value2 1
value1 value2 2

I am stuck at the point where i dont know how to read this json and save the data in my schema (struct) to create multiple entries like-

var users = []User{{key1: "value1", "key2": "value2, "key" :1}, {key1: "value1", "key2": "value2, "key" :2}}
db.Create(&users)

Please guide me to a possible solution as i am new to Go. Let me know for more clarifications. Thanks

Structs needed

  1. Request json
type BodyJson struct {
    Key []int `json:key`
}
  1. User table struct for gorm
type User struct {
    Key  int    `gorm:"column:key"`
    Key1 string `gorm:"column:key1"`
    Key2 string `gorm:"column:key2"`
}

Unmarshal body json to BodyJson struct var

var bodyJson BodyJson
err := json.Unmarshal([]byte(body_json_string), &bodyJson)

loop over bodyJson.Key array and populate an [] of User with this key, key1 and key2.

Then save the users with

db.Create(&users)

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM