实现GetPlanByID
This commit is contained in:
@@ -58,9 +58,10 @@ func (Plan) TableName() string {
|
|||||||
type SubPlan struct {
|
type SubPlan struct {
|
||||||
gorm.Model
|
gorm.Model
|
||||||
|
|
||||||
ParentPlanID uint `gorm:"not null;index" json:"parent_plan_id"` // 父计划的ID
|
ParentPlanID uint `gorm:"not null;index" json:"parent_plan_id"` // 父计划的ID
|
||||||
ChildPlanID uint `gorm:"not null;index" json:"child_plan_id"` // 子计划的ID (它本身也是一个 Plan)
|
ChildPlanID uint `gorm:"not null;index" json:"child_plan_id"` // 子计划的ID (它本身也是一个 Plan)
|
||||||
Order int `gorm:"not null" json:"order"` // 在父计划中的执行顺序
|
Order int `gorm:"not null" json:"order"` // 在父计划中的执行顺序
|
||||||
|
ChildPlan *Plan `gorm:"-" json:"child_plan"` // 完整子计划数据,仅内存中
|
||||||
}
|
}
|
||||||
|
|
||||||
// TableName 自定义 GORM 使用的数据库表名
|
// TableName 自定义 GORM 使用的数据库表名
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package repository
|
package repository
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
|
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
@@ -47,3 +49,47 @@ func (r *gormPlanRepository) GetBasicPlanByID(id uint) (*models.Plan, error) {
|
|||||||
}
|
}
|
||||||
return &plan, nil
|
return &plan, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetPlanByID 根据ID获取计划,包含子计划和任务详情
|
||||||
|
func (r *gormPlanRepository) GetPlanByID(id uint) (*models.Plan, error) {
|
||||||
|
var plan models.Plan
|
||||||
|
|
||||||
|
// 先获取基本计划信息
|
||||||
|
result := r.db.First(&plan, id)
|
||||||
|
if result.Error != nil {
|
||||||
|
return nil, result.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据内容类型加载关联数据
|
||||||
|
switch plan.ContentType {
|
||||||
|
case models.PlanContentTypeSubPlans:
|
||||||
|
// 加载子计划引用
|
||||||
|
var subPlans []models.SubPlan
|
||||||
|
result = r.db.Where("parent_plan_id = ?", plan.ID).Order("order").Find(&subPlans)
|
||||||
|
if result.Error != nil {
|
||||||
|
return nil, result.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// 递归加载每个子计划的完整信息
|
||||||
|
for i := range subPlans {
|
||||||
|
// 递归调用确保子计划数据可以被获取
|
||||||
|
// 注意:SubPlan结构体中没有ChildPlan字段,所以这里只是递归获取确保数据完整性
|
||||||
|
childPlan, err := r.GetPlanByID(subPlans[i].ChildPlanID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
subPlans[i].ChildPlan = childPlan
|
||||||
|
}
|
||||||
|
|
||||||
|
plan.SubPlans = subPlans
|
||||||
|
case models.PlanContentTypeTasks:
|
||||||
|
// 加载任务
|
||||||
|
result = r.db.Preload("Tasks", func(taskDB *gorm.DB) *gorm.DB {
|
||||||
|
return taskDB.Order("order")
|
||||||
|
}).Find(&plan)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("未知的计划内容类型: %v; 计划ID: %v", plan.ContentType, plan.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &plan, nil
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user