学会了查找(select)和插入(insert),我们也要进入下一阶段,那就是删除(delete)。
删除(delete)
根据课程内容,删除有两种方式,一种是可见删除,一种是不可见删除。
- 可见删除:资料还存在于用户表里,但是查询时不会显示。
- 不可见删除:资料不存在在表里,也无法找回显示。
在这里,我要特别提醒,不要随随便便删除东西,否则…… 我们删库,我们跑路,我们进局子,我们踩缝纫机。
处理数据库
一般情况下,我们可能会进行如下代码操作:
delete from comment_entities where comment_id =2;
但这种情况下一定要注意有where,否则整张表都留不住。
现在我们的表长这样:
确定service层
func DeleteComment(commentId string) {
CommentDbService.Db.Delete(&Entity.CommentEntity{}, commentId)
}
但我试过上述代码,没删掉,所以老老实实用了where:
// 要有删除评论的功能
func DeleteComment(commentId string) {
//err = db.Where("id = ?", commentId).Delete(&CommentEntity{}).Error
CommentDbService.Db.Where("comment_id = ?", commentId).Delete(&Entity.CommentEntity{})
}
上述代码便是删除所用。
确定controller层
func DeleteComment(c *gin.Context) {
// 从 URL 参数中获取要删除的用户ID
commentId := c.Query("CommentId")
// 执行删除逻辑,这里可以根据 userID 去删除用户
CommentService.DeleteComment(commentId)
// 返回响应
c.JSON(http.StatusOK, gin.H{"message": "Comment deleted successfully"})
}
上述注释已经表明了每个函数的作用。
添加路径
comment.DELETE("/douyin/comment/del", CommentController.DeleteComment)
如此一来,路径为:
http://localhost:9180/Comment/douyin/comment/del
检验
由于我们的返回响应设定为
"message": "Comment deleted successfully",因此,当返回后出现这一段则说明成功,表格也成功删除了这一项。
注:表格内容不一样是因为我刚刚写了update。