实现DeleteFeedingPlan
This commit is contained in:
@@ -18,6 +18,9 @@ type FeedPlanRepo interface {
|
||||
|
||||
// CreateFeedingPlan 创建饲料计划
|
||||
CreateFeedingPlan(feedingPlan *model.FeedingPlan) error
|
||||
|
||||
// DeleteFeedingPlan 删除饲料计划及其所有子计划和步骤
|
||||
DeleteFeedingPlan(id uint) error
|
||||
}
|
||||
|
||||
type feedPlanRepo struct {
|
||||
@@ -59,6 +62,45 @@ func (f *feedPlanRepo) CreateFeedingPlan(feedingPlan *model.FeedingPlan) error {
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteFeedingPlan 删除饲料计划及其所有子计划和步骤
|
||||
func (f *feedPlanRepo) DeleteFeedingPlan(id uint) error {
|
||||
return f.db.Transaction(func(tx *gorm.DB) error {
|
||||
// 递归删除计划及其所有子计划
|
||||
if err := f.deleteFeedingPlanWithTx(tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// deleteFeedingPlanWithTx 在事务中递归删除饲料计划
|
||||
func (f *feedPlanRepo) deleteFeedingPlanWithTx(tx *gorm.DB, id uint) error {
|
||||
// 先查找计划及其子计划
|
||||
var plan model.FeedingPlan
|
||||
if err := tx.Where("id = ?", id).Preload("SubPlans").First(&plan).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 递归删除所有子计划
|
||||
for _, subPlan := range plan.SubPlans {
|
||||
if err := f.deleteFeedingPlanWithTx(tx, subPlan.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 删除该计划的所有步骤
|
||||
if err := tx.Where("plan_id = ?", id).Delete(&model.FeedingPlanStep{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 删除计划本身
|
||||
if err := tx.Delete(&model.FeedingPlan{}, id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// createFeedingPlanWithTx 在事务中递归创建饲料计划
|
||||
func (f *feedPlanRepo) createFeedingPlanWithTx(tx *gorm.DB, feedingPlan *model.FeedingPlan) error {
|
||||
// 先创建计划主体
|
||||
@@ -84,7 +126,7 @@ func (f *feedPlanRepo) createFeedingPlanWithTx(tx *gorm.DB, feedingPlan *model.F
|
||||
}
|
||||
}
|
||||
|
||||
// 处理子计划 - 重新填充子计划编号
|
||||
// 处理子计划 - 重新填充子计划编号和父ID
|
||||
sort.Slice(feedingPlan.SubPlans, func(i, j int) bool {
|
||||
// 如果OrderInParent为nil,放在最后
|
||||
if feedingPlan.SubPlans[i].OrderInParent == nil {
|
||||
|
||||
Reference in New Issue
Block a user