实现修改猪营养需求
This commit is contained in:
@@ -62,6 +62,7 @@ type Service interface {
|
||||
UpdatePigType(ctx context.Context, pigType *models.PigType) error
|
||||
DeletePigType(ctx context.Context, id uint32) error
|
||||
ListPigTypes(ctx context.Context, opts repository.PigTypeListOptions, page, pageSize int) ([]models.PigType, int64, error)
|
||||
UpdatePigTypeNutrientRequirements(ctx context.Context, pigTypeID uint32, requirements []models.PigNutrientRequirement) error
|
||||
}
|
||||
|
||||
// recipeServiceImpl 是 RecipeService 的实现
|
||||
@@ -526,3 +527,38 @@ func (s *recipeServiceImpl) ListPigTypes(ctx context.Context, opts repository.Pi
|
||||
}
|
||||
return pigTypes, total, nil
|
||||
}
|
||||
|
||||
// UpdatePigTypeNutrientRequirements 实现了全量更新猪类型营养需求的核心业务逻辑
|
||||
func (s *recipeServiceImpl) UpdatePigTypeNutrientRequirements(ctx context.Context, pigTypeID uint32, requirements []models.PigNutrientRequirement) error {
|
||||
serviceCtx := logs.AddFuncName(ctx, s.ctx, "UpdatePigTypeNutrientRequirements")
|
||||
|
||||
// 1. 检查猪类型是否存在
|
||||
if _, err := s.pigTypeRepo.GetPigTypeByID(serviceCtx, pigTypeID); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrPigTypeNotFound
|
||||
}
|
||||
return fmt.Errorf("获取待更新营养需求的猪类型失败: %w", err)
|
||||
}
|
||||
|
||||
// 2. 在事务中执行替换操作
|
||||
err := s.uow.ExecuteInTransaction(serviceCtx, func(tx *gorm.DB) error {
|
||||
// 2.1. 删除旧的关联记录
|
||||
if err := s.pigTypeRepo.DeletePigNutrientRequirementsByPigTypeIDTx(serviceCtx, tx, pigTypeID); err != nil {
|
||||
return err // 错误已在仓库层封装,直接返回
|
||||
}
|
||||
|
||||
// 2.2. 创建新的关联记录
|
||||
if err := s.pigTypeRepo.CreateBatchPigNutrientRequirementsTx(serviceCtx, tx, requirements); err != nil {
|
||||
return err // 错误已在仓库层封装,直接返回
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("更新猪类型营养需求事务执行失败: %w", err)
|
||||
}
|
||||
|
||||
// 3. 操作成功,直接返回 nil
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user