[英]Multiple update using GORM in Golang
I am trying to make APIs using GIN and GORM.我正在尝试使用 GIN 和 GORM 制作 API。 Now i have stucked in one of the APIs.
现在我坚持使用其中一个 API。 This API will create multiple entries in the DB.
这个 API 将在数据库中创建多个条目。 I have the json body like this.
我有这样的 json 机身。 The size of array will vary.
数组的大小会有所不同。
{
"key" : [1,2]
}
With this, I have some other parameter that i am getting from the url-有了这个,我有一些其他的参数,我从 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 的数据在 DB 上创建多个条目 [1,2] -
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-我被困在我不知道如何阅读此 json 并将数据保存在我的架构(结构)中以创建多个条目的地步,例如-
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.请指导我找到可能的解决方案,因为我是 Go 的新手。 Let me know for more clarifications.
让我知道更多说明。 Thanks
谢谢
Structs needed需要的结构
type BodyJson struct {
Key []int `json:key`
}
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将主体 json 解组为 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.循环
bodyJson.Key
数组并使用此键、key1 和 key2 填充User
的 []。
Then save the users with然后保存用户
db.Create(&users)
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.