在Golang中使用GORM进行多次更新

huangapple go评论111阅读模式
英文:

Multiple update using GORM in Golang

问题

我正在尝试使用GIN和GORM创建API。现在我在其中一个API中遇到了问题。这个API将在数据库中创建多个条目。
我有以下的JSON请求体。数组的大小会有所变化。

  1. {
  2. "key": [1, 2]
  3. }

除此之外,我还从URL中获取了其他参数-

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

现在我想要使用key1和key2的数据在数据库中创建多个条目[1, 2],如下所示-

Key1 Key2 key
value1 value2 1
value1 value2 2

我在不知道如何读取这个JSON并将数据保存到我的模式(结构体)以创建多个条目的地方卡住了,类似于-

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

请指导我可能的解决方案,因为我对Go语言还不熟悉。
如果需要更多解释,请告诉我。谢谢。

英文:

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.

  1. {
  2. "key" : [1,2]
  3. }

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

  1. key1 := c.Param("value1")
  2. 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-

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

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

答案1

得分: 1

结构体需求

  1. 请求 JSON
  1. type BodyJson struct {
  2. Key []int `json:"key"`
  3. }
  1. 用于 gorm 的用户表结构体
  1. type User struct {
  2. Key int `gorm:"column:key"`
  3. Key1 string `gorm:"column:key1"`
  4. Key2 string `gorm:"column:key2"`
  5. }

将请求的 JSON 解析为 BodyJson 结构体变量

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

遍历 bodyJson.Key 数组,并使用该 key、key1 和 key2 填充一个 User 的切片。

然后使用以下代码保存用户:

  1. db.Create(&users)

希望这可以帮到你。

英文:

Structs needed

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

Unmarshal body json to BodyJson struct var

  1. var bodyJson BodyJson
  2. 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

  1. db.Create(&users)

Hope this helps.

huangapple
  • 本文由 发表于 2022年8月22日 21:50:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/73446234.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定