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 code I'm working with:
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,
/* here, I don'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: "size",
Color: "color",
Quantity: "quantity", /* Converting Strings to Numbers */
},
},
}
database.DB.Create(&product)
return c.JSON(product)
}