Files

71 lines
1.5 KiB
Go
Raw Permalink Normal View History

2025-09-24 01:07:21 +08:00
package article
import (
"net/http"
"toutoukan/init/databaseInit"
"github.com/gin-gonic/gin"
)
// DeleteArticleRequest 删除文章的请求参数
type DeleteArticleRequest struct {
2025-09-24 20:57:23 +08:00
ArticleID int64 `json:"article_id" binding:"required,min=1"`
2025-09-24 01:07:21 +08:00
}
2025-09-24 20:57:23 +08:00
// DeleteArticle 删除文章(如果数据库支持级联删除)
2025-09-24 01:07:21 +08:00
func DeleteArticle(c *gin.Context) {
var req DeleteArticleRequest
2025-09-24 20:57:23 +08:00
// 1. 解析请求参数
2025-09-24 01:07:21 +08:00
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "参数解析失败",
"detail": err.Error(),
})
return
}
2025-09-24 20:57:23 +08:00
// 2. 开启数据库事务
2025-09-24 01:07:21 +08:00
tx := databaseInit.UserDB.Begin()
if tx.Error != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "开启事务失败: " + tx.Error.Error(),
})
return
}
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
2025-09-24 20:57:23 +08:00
// 3. 只删除文章主记录,由数据库自动处理关联数据
2025-09-24 01:07:21 +08:00
if err := tx.Table("article_list").
Where("articleId = ?", req.ArticleID).
Delete(nil).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusInternalServerError, gin.H{
"error": "删除文章失败: " + err.Error(),
})
return
}
2025-09-24 20:57:23 +08:00
// 4. 提交事务
2025-09-24 01:07:21 +08:00
if err := tx.Commit().Error; err != nil {
tx.Rollback()
c.JSON(http.StatusInternalServerError, gin.H{
"error": "提交删除操作失败: " + err.Error(),
})
return
}
2025-09-24 20:57:23 +08:00
// 5. 返回成功响应
2025-09-24 01:07:21 +08:00
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "文章及关联数据已全部删除",
"data": gin.H{
"deleted_article_id": req.ArticleID,
},
})
}