【Go实战 | 电商平台】(11) 更新商品

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 验证服务

  • 发送请求

在这里插入图片描述

  • 响应返回

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45304503/article/details/121551904
今日推荐