关于Server层的商品修改的一些疑问

来源:1-21 新增、修改和删除商品接口

burningx

2021-09-26 20:22:54

我看到老师写的代码在保存数据库前,并没有对可修改的字段进行判断是否有传值 见下图
图片描述

这样写的话,web 层请求修改接口的时候,如果我只传 IsHot、IsNew、OnSale 字段的话,其他字段不会覆盖空值吗?还是说我有地方没看明白呢?


下面是我写的一个接口

func (s *Service) UpdatePost(c context.Context, req *qapb.CreatePostRequest) (*emptypb.Empty, error) {
	post, _ := s.Mysql.GetPostDetail(c, req.Id)
	if post == nil {
		return nil, status.Errorf(codes.NotFound, "问题不存在")
	}
	if req.CategoryId != 0 {
		category, _ := s.Mysql.GetOneCategory(c, req.CategoryId)
		if category == nil {
			return nil, status.Errorf(codes.NotFound, "分类不存在")
		}
		post.CategoryID = uint32(req.CategoryId)
		post.Category = category
	}

	post.Title = req.Title
	post.Content = &req.Content
	post.Contact = &req.Contact
	post.Status = uint8(req.Status)
	post.IsCommon = req.IsCommon
	post.IsGood = req.IsGood

	if err := s.Mysql.UpdatePost(c, post); err != nil {
		return nil, err
	}

	return &emptypb.Empty{}, nil
}

不对字段进行判断的话,只传部分字段,其他都赋空值了。
图片描述

测试代码

updateCases := []struct {
	name     string
	id       uint32
	title    string
	content  string
	contact  string
	status   int32
	isGood   bool
	isCommon bool
}{
	{
		name:    "update_post_title.content.contact",
		id:      1,
		title:   "update_title1",
		content: "update_content1",
		contact: "update_contact1",
	},
	{
		name:   "update_post_status1",
		id:     1,
		status: 1,
	},
	{
		name:     "update_post_isgoodfalse.iscommontrue",
		id:       1,
		isGood:   false,
		isCommon: true,
	},
}

for _, uu := range updateCases {
	t.Run(uu.name, func(t *testing.T) {

		createPostRequest := qapb.CreatePostRequest{
			Id: int32(uu.id),
		}

		if uu.name == "update_post_title.content.contact" {
			createPostRequest.Title = uu.title
			createPostRequest.Content = uu.content
			createPostRequest.Contact = uu.contact
		}

		if uu.name == "update_post_status1" {
			createPostRequest.Status = uu.status
		}

		if uu.name == "update_post_isgoodfalse.iscommontrue" {
			createPostRequest.IsCommon = uu.isCommon
			createPostRequest.IsGood = uu.isGood
		}

		if _, err = s.UpdatePost(c, &createPostRequest); err != nil {
			t.Errorf("cannot update post: %v", err)
		}

	})
}
写回答

1回答

bobby

2021-09-27

课程在讲解gorm的基础的时候提到过。gorm在生成sql的时候会将空指给忽略掉

2

0 学习 · 1399 问题

查看课程