Browse Source

组件分类管理

huangyan 8 months ago
parent
commit
0c254c7118

+ 20 - 2
app/controller/componentClassify.go

@@ -20,7 +20,6 @@ func GetComponentClassify(c *gin.Context) {
 	} else {
 		e.ResponseSuccess(c, classify)
 	}
-
 }
 
 // AddComponentClassify 添加组件分类
@@ -63,5 +62,24 @@ func DeleteComponentClassify(c *gin.Context) {
 
 // UpdateComponentClassify 更新组件分类
 func UpdateComponentClassify(c *gin.Context) {
-
+	var componentClass model.ComponentClassify
+	s := c.Query("id")
+	err := c.ShouldBindJSON(&componentClass)
+	if err != nil {
+		e.ResponseWithMsg(c, e.JSONParsingFailed, e.JSONParsingFailed.GetMsg())
+		return
+	}
+	validate := validator.New()
+	err = validate.Var(s, "required,numeric")
+	if err != nil {
+		e.ResponseWithMsg(c, e.ERROR, "id不能为空")
+		return
+	}
+	atoi, _ := strconv.Atoi(s)
+	id, err := unity.UpdateById(atoi, &componentClass)
+	if err != nil {
+		e.ResponseWithMsg(c, e.ERROR, err.Error())
+		return
+	}
+	e.ResponseSuccess(c, id)
 }

+ 30 - 7
app/model/componentClassify.go

@@ -29,12 +29,35 @@ func (cc ComponentClassify) AddComponentClassify(cclass ComponentClassify) (Comp
 
 // GetComponentClassify 获取组件分类
 func (cc ComponentClassify) GetComponentClassify() ([]ComponentClassify, error) {
-	//TODO implement me
-	var parent []ComponentClassify
-	var child []ComponentClassify
-	global.DBLink.Where("parent_id = 0").Find(&parent)
-	for _, classify := range parent {
-		global.DBLink.Where("parent_id =?", classify.ID).Find(&child)
+	var roots []ComponentClassify
+	err := global.DBLink.Where("parent_id = 0").Find(&roots).Error
+	if err != nil {
+		return nil, err
+	}
+
+	for i := range roots {
+		err = recursiveFetchChildren(global.DBLink, &roots[i])
+		if err != nil {
+			return nil, err
+		}
+	}
+	return roots, nil
+}
+
+// 递归获取分类
+func recursiveFetchChildren(db *gorm.DB, parent *ComponentClassify) error {
+	var children []ComponentClassify
+	err := db.Where("parent_id = ?", parent.ID).Find(&children).Error
+	if err != nil {
+		return err
+	}
+
+	for _, child := range children {
+		err = recursiveFetchChildren(db, &child)
+		if err != nil {
+			return err
+		}
+		parent.Child = append(parent.Child, child)
 	}
-	return parent, nil
+	return nil
 }

+ 1 - 0
app/routers/componentclass.go

@@ -10,4 +10,5 @@ func ComponentClassRouter(r *gin.Engine) {
 	group.GET("/componentclass", controller.GetComponentClassify)
 	group.POST("/addcomponentclass", controller.AddComponentClassify)
 	group.DELETE("/componentclass", controller.DeleteComponentClassify)
+	group.PUT("/componentclass", controller.UpdateComponentClassify)
 }