修改文评功能

This commit is contained in:
JACKYMYPERSON
2025-09-24 20:57:23 +08:00
parent 98fc0e6b8e
commit 1b2ba486cf
4 changed files with 222 additions and 166 deletions

View File

@@ -9,14 +9,14 @@ import (
// DeleteArticleRequest 删除文章的请求参数
type DeleteArticleRequest struct {
ArticleID int64 `json:"article_id" binding:"required,min=1"` // 要删除的文章ID
ArticleID int64 `json:"article_id" binding:"required,min=1"`
}
// DeleteArticle 删除文章(处理外键关联
// DeleteArticle 删除文章(如果数据库支持级联删除
func DeleteArticle(c *gin.Context) {
var req DeleteArticleRequest
// 解析请求参数
// 1. 解析请求参数
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "参数解析失败",
@@ -25,7 +25,7 @@ func DeleteArticle(c *gin.Context) {
return
}
// 开启事务(确保所有删除操作要么全部成功,要么全部失败)
// 2. 开启数据库事务
tx := databaseInit.UserDB.Begin()
if tx.Error != nil {
c.JSON(http.StatusInternalServerError, gin.H{
@@ -39,29 +39,7 @@ func DeleteArticle(c *gin.Context) {
}
}()
// 步骤1先删除用户投票记录因为依赖文章ID和选项ID
if err := tx.Table("user_votes").
Where("vote_article_id = ?", req.ArticleID).
Delete(nil).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusInternalServerError, gin.H{
"error": "删除用户投票记录失败: " + err.Error(),
})
return
}
// 步骤2再删除文章选项因为依赖文章ID
if err := tx.Table("article_options").
Where("vote_article_id = ?", req.ArticleID).
Delete(nil).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusInternalServerError, gin.H{
"error": "删除文章选项失败: " + err.Error(),
})
return
}
// 步骤3最后删除文章主记录
// 3. 只删除文章主记录,由数据库自动处理关联数据
if err := tx.Table("article_list").
Where("articleId = ?", req.ArticleID).
Delete(nil).Error; err != nil {
@@ -72,7 +50,7 @@ func DeleteArticle(c *gin.Context) {
return
}
// 提交事务
// 4. 提交事务
if err := tx.Commit().Error; err != nil {
tx.Rollback()
c.JSON(http.StatusInternalServerError, gin.H{
@@ -81,7 +59,7 @@ func DeleteArticle(c *gin.Context) {
return
}
// 返回成功响应
// 5. 返回成功响应
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "文章及关联数据已全部删除",