1. 更新商品
1.1 路由接口注册
authed.PUT("product/:id", api.UpdateProduct)
1.2 接口函数编写
1.2.1 service层
type UpdateProductService struct {
ID uint `form:"id" json:"id"`
Name string `form:"name" json:"name"`
CategoryID int `form:"category_id" json:"category_id"`
Title string `form:"title" json:"title" binding:"required,min=2,max=100"`
Info string `form:"info" json:"info" binding:"max=1000"`
ImgPath string `form:"img_path" json:"img_path"`
Price string `form:"price" json:"price"`
DiscountPrice string `form:"discount_price" json:"discount_price"`
OnSale bool `form:"on_sale" json:"on_sale"`
Num string `form:"num" json:"num"`
}
func (service *UpdateProductService) Update(id string) serializer.Response {
...
}
1.2.2 api层
updateProductService := service.UpdateProductService{
}
c.ShouldBind(&updateProductService)
- 调用这个更新服务对象的方法,注意这个
id
是路由上面的那个id
res := updateProductService.Update(c.Param("id"))
c.JSON(200, res)
func UpdateProduct(c *gin.Context) {
updateProductService := service.UpdateProductService{
}
if err := c.ShouldBind(&updateProductService); err == nil {
res := updateProductService.Update(c.Param("id"))
c.JSON(200, res)
} else {
c.JSON(200, ErrorResponse(err))
logging.Info(err)
}
}
1.3 服务函数编写
var category model.Category
model.DB.Model(&model.Category{
}).First(&category,service.CategoryID)
var product model.Product
model.DB.Model(&model.Product{
}).First(&product,id)
product.Name=service.Name
product.Category=category
product.CategoryID=uint(service.CategoryID)
product.Title=service.Title
product.Info=service.Info
product.ImgPath=service.ImgPath
product.Price=service.Price
product.DiscountPrice=service.DiscountPrice
product.OnSale=service.OnSale
err := model.DB.Save(&product).Error
return serializer.Response{
Status: code,
Msg: e.GetMsg(code),
}
1.4 验证服务
![在这里插入图片描述](https://img-blog.csdnimg.cn/1d9f731722b9409a83a0e60e558f46b0.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5bCP55Sf5Yeh5LiA,size_20,color_FFFFFF,t_70,g_se,x_16)
![在这里插入图片描述](https://img-blog.csdnimg.cn/5d4b3ff8104247138222b6d11a36fa26.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5bCP55Sf5Yeh5LiA,size_20,color_FFFFFF,t_70,g_se,x_16)