后端实践:使用GORM对数据库进行增删改查(六)改|青训营;

74 阅读2分钟

我们的增删改查很快就到了最后一步,也就是我们常说的改(update)。在改动的过程中,我们需要注意什么东西该改,什么东西不改;是只改一个,还是要改一列。

更新(update)

更新一般有两种发送请求的方法,一种是PUT,一种和增加一样,是POST。 对于这两个的区别,我们只需要记住,一个是更改整个表格每一行(put),另一个是只更改其中一个(post)。 他们两个的区别,我找了两个对比,可以点击此处点击此处

处理数据库

我们需要在数据库中执行如下语句:

update comment_entities set content='泰裤辣' where comment_id ='12';

注意,我们不能少写where字句,否则整张表都会发生变动。

确定service层

service层是最简单的,确定了SQL语句之后就能把代码完成。

// 更新评论
func UpdateComment(comment Entity.CommentEntity) {
	CommentDbService.Db.Model(&Entity.CommentEntity{}).Where(&Entity.CommentEntity{CommentId: comment.CommentId}).Updates(comment)
}

注意的是,我用的Update是传递了一整个对象,即一整行进去,哪怕值没有变动也要穿进去一个相同的。

确定controller层

// 更新评论
func UpdateComment(c *gin.Context) {
	var req UpdateCommentRequest

	// 解析请求体中的 JSON 数据
	if err := c.ShouldBindJSON(&req); err != nil {
		// 处理解析错误
		ApiState.ArgErrApiResult(c, err.Error())
		return
	}

	// 创建 CommentEntity 对象
	com := Entity.CommentEntity{
		CommentId: req.CommentId,
		UserId:    req.UserID,
		VideoId:   req.VideoID,
		Content:   req.Content,
		Calendar:  req.Calendar,
	}

	// 调用 CommentService 的 AddComment 函数
	CommentService.UpdateComment(com)

	// 返回响应
	ApiState.ResponseSuccess(c, com)
}

大家可以发现,这次的设定和insert有所不同,原因在于本次实验的CommentId是不变的,因此要对req进行改进,即添加属性CommentId:

type UpdateCommentRequest struct {
	CommentId string `json:"CommentId"`
	UserID    int    `json:"UserId"`
	VideoID   int    `json:"VideoId"`
	Calendar  string `json:"Calendar"`
	Content   string `json:"Content"`
}

添加路径

本次路径使用了PUT: comment.PUT("/douyin/comment/update", CommentController.UpdateComment)

检查

在更新之前,数据库表如图所示:

1692244440885.png

更新操作:

1692244482526.png

更新后:

1692244644941.png

我们可以发现它实现了我们的改变。