如何使用GORM创建具有嵌套/解组数据的Many2Many的POST方法?

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

How to create post method GORM Many2Many with nested/unmarshal data?

问题

我正在使用GoFiber、GORM和MySQL数据库。我正在编写POST方法将产品数据写入数据库。我发现我要写入的数据类型是"嵌套数据"或"解组数据",但是关于Golang或特定的GORM Many2Many的POST方法的文档很少。

我使用的结构体如下:

package models

type Product struct {
  Model
  Code        string  `json:"code"`
  Title       string  `json:"title"`
  Description string  `json:"description"`
  Image       string  `json:"image"`
  Price       float64 `json:"price"`
  Stocks      []Stock `json:"stock,omitempty" gorm:"many2many:product_stocks;"`
}

type Stock struct {
  Model
  Size      string  `json:"size"`
  Color     string  `json:"color"`
  Quantity  int     `json:"quantity"` 
}

JSON数据:

{
  "code": "SS2022VNMNYU7W",
  "title": "Title Demo",
  "description": "Description Demo",
  "image": "path",
  "price": "100",
  "stock": [
    {
      "size": "m",
      "color": "red",
      "quantity": "50"
    },
    {
      "size": "m",
      "color": "yellow",
      "quantity": "50"
    },
    {
      "size": "l",
      "color": "red",
      "quantity": "20"
    },
    {
      "size": "l",
      "color": "blue",
      "quantity": "30"
    }
  ]
}

这是我正在使用的控制器代码:

func CreateProduct(c *fiber.Ctx) error {
  var data map[string]string
  if err := c.BodyParser(&data); err != nil {
    return err
  }
  
  PriceItem, _ := strconv.Atoi(data["price"])
  product := models.Product{
    Code:         data["code"],
    Title:        data["title"],
    Description:  data["description"],
    Image:        data["image"],
    Price:        PriceItem,
    
    /* 在这里,我不知道如何将库存输入产品数据,因为这个库存会因产品而异。例如,尺寸数量的变化,颜色数量的变化。 */
    Stocks: []models.Stock{
      {
        Size:     "size",
        Color:    "color",
        Quantity: "quantity", /* 将字符串转换为数字 */
      },
    },
  }
  database.DB.Create(&product)
  
  return c.JSON(product)
}
英文:

I am using GoFiber, GORM and mysql database. I am writing POST METHOD to write product data to DB. I see the data type I'm trying to write is "nested data" or "unmarshal data", but there's not much documentation for golang or specifically GORM Many2Many for POST METHOD.

The structures that I use:

package models

type Product struct {
  Model
  Code        string  `json:"code"`
  Title       string  `json:"title"`
  Description string  `json:"description"`
  Image       string  `json:"image"`
  Price       float64 `json:"price"`
  Stocks      []Stock `json:"stock,omitempty" gorm:"many2many:product_stocks;"`
}

type Stock struct {
  Model
  Size      string  `json:"size"`
  Color     string  `json:"color"`
  Quantity  int     `json:"quantity"` 
}

Json data:

{
  "code": "SS2022VNMNYU7W",
  "title": "Title Demo",
  "description": "Description Demo",
  "image": "path",
  "price": "100",
  "stock": [
    {
      "size": "m",
      "color": "red",
      "quantity": "50"
    },
    {
      "size": "m",
      "action": "yellow",
      "quantity": "50"
    },
    {
      "size": "l",
      "action": "red",
      "quantity": "20"
    },
    {
      "size": "l",
      "action": "blue",
      "quantity": "30"
    }
  ]
 }

Here is the <controllers> code I'm working with:

func CreateProduct(c *fiber.Ctx) error {
  var data map[string]string
  if err := c.BodyParser(&amp;data); err != nil {
    return err
  }
  
  PriceItem, _ := strconv.Atoi(data[&quot;price&quot;])
  product := models.Product{
    Code:         data[&quot;code&quot;],
    Title:        data[&quot;title&quot;],
    Description:  data[&quot;description&quot;],
    Image:        data[&quot;image&quot;],
    Price:        PriceItem,
    
    /* here, I don&#39;t know how to input stock into product data because this stock varies by product. For example, changes in the number of sizes, changes in the number of colors. */
    Stocks: []models.Stock{
      {
        Size:     &quot;size&quot;,
        Color:    &quot;color&quot;,
        Quantity: &quot;quantity&quot;, /* Converting Strings to Numbers */
      },
    },
  }
  database.DB.Create(&amp;product)
  
  return c.JSON(product)
}

答案1

得分: 1

在 JSON 中,你可以直接将价格(price)和数量(quantity)设置为整数,然后可以直接使用 Product 模型和 BodyParser

{
  "code": "SS2022VNMNYU7W",
  "title": "Title Demo",
  "description": "Description Demo",
  "image": "path",
  "price": 100, <- 作为整数
  "stock": [
    {
      "size": "m",
      "color": "red",
      "quantity": 50 <- 作为整数
    },
    {
      "size": "m",
      "action": "yellow",
      "quantity": 50 <- 作为整数
    },
    {
      "size": "l",
      "action": "red",
      "quantity": 20 <- 作为整数
    },
    {
      "size": "l",
      "action": "blue",
      "quantity": 30 <- 作为整数
    }
  ]
}

然后在 CreatePost 方法中:

func CreateProduct(c *fiber.Ctx) error {
  product := new(Product)
  if err := c.BodyParser(&product); err != nil {
    return err
  }
  
  database.DB.Create(&product)
  
  return c.JSON(product)
}
英文:

In json you can directly pass price and quantity has integer and then you can directly use Product model with BodyParser

{
  &quot;code&quot;: &quot;SS2022VNMNYU7W&quot;,
    &quot;title&quot;: &quot;Title Demo&quot;,
    &quot;description&quot;: &quot;Description Demo&quot;,
    &quot;image&quot;: &quot;path&quot;,
    &quot;price&quot;: 100, &lt;- as int
    &quot;stock&quot;: [
    {
      &quot;size&quot;: &quot;m&quot;,
      &quot;color&quot;: &quot;red&quot;,
      &quot;quantity&quot;: 50 &lt;- as int
    },
    {
      &quot;size&quot;: &quot;m&quot;,
      &quot;action&quot;: &quot;yellow&quot;,
      &quot;quantity&quot;: 50 &lt;- as int
    },
    {
      &quot;size&quot;: &quot;l&quot;,
      &quot;action&quot;: &quot;red&quot;,
      &quot;quantity&quot;: 20 &lt;- as int
    },
    {
      &quot;size&quot;: &quot;l&quot;,
      &quot;action&quot;: &quot;blue&quot;,
      &quot;quantity&quot;: 30 &lt;- as int
    }
  ]
}

Then in CreatePost method

func CreateProduct(c *fiber.Ctx) error {
  product := new(Product)
  if err := c.BodyParser(&amp;product); err != nil {
    return err
  }
  
  database.DB.Create(&amp;product)
  
  return c.JSON(product)
}

huangapple
  • 本文由 发表于 2022年6月10日 14:24:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/72569908.html
匿名

发表评论

匿名网友

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

确定