拓展接口响应
This commit is contained in:
@@ -11,12 +11,19 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// NutrientListOptions 定义了查询营养种类列表时的筛选条件
|
||||
type NutrientListOptions struct {
|
||||
Name *string
|
||||
RawMaterialName *string
|
||||
OrderBy string
|
||||
}
|
||||
|
||||
// NutrientRepository 定义了与营养种类相关的数据库操作接口
|
||||
type NutrientRepository interface {
|
||||
CreateNutrient(ctx context.Context, nutrient *models.Nutrient) error
|
||||
GetNutrientByID(ctx context.Context, id uint32) (*models.Nutrient, error)
|
||||
GetNutrientByName(ctx context.Context, name string) (*models.Nutrient, error)
|
||||
ListNutrients(ctx context.Context, page, pageSize int) ([]models.Nutrient, int64, error)
|
||||
ListNutrients(ctx context.Context, opts NutrientListOptions, page, pageSize int) ([]models.Nutrient, int64, error)
|
||||
UpdateNutrient(ctx context.Context, nutrient *models.Nutrient) error
|
||||
DeleteNutrient(ctx context.Context, id uint32) error
|
||||
}
|
||||
@@ -61,19 +68,36 @@ func (r *gormNutrientRepository) GetNutrientByName(ctx context.Context, name str
|
||||
}
|
||||
|
||||
// ListNutrients 列出所有营养种类(分页),并预加载关联的原料信息
|
||||
func (r *gormNutrientRepository) ListNutrients(ctx context.Context, page, pageSize int) ([]models.Nutrient, int64, error) {
|
||||
func (r *gormNutrientRepository) ListNutrients(ctx context.Context, opts NutrientListOptions, page, pageSize int) ([]models.Nutrient, int64, error) {
|
||||
repoCtx := logs.AddFuncName(ctx, r.ctx, "ListNutrients")
|
||||
var nutrients []models.Nutrient
|
||||
var total int64
|
||||
|
||||
db := r.db.WithContext(repoCtx).Model(&models.Nutrient{})
|
||||
|
||||
// 应用筛选条件
|
||||
if opts.Name != nil && *opts.Name != "" {
|
||||
db = db.Where("name LIKE ?", "%"+*opts.Name+"%")
|
||||
}
|
||||
|
||||
// 如果传入了原料名称,则使用子查询进行筛选
|
||||
if opts.RawMaterialName != nil && *opts.RawMaterialName != "" {
|
||||
subQuery := r.db.Model(&models.RawMaterialNutrient{}).
|
||||
Select("nutrient_id").
|
||||
Joins("JOIN raw_materials ON raw_materials.id = raw_material_nutrients.raw_material_id").
|
||||
Where("raw_materials.name LIKE ?", "%"+*opts.RawMaterialName+"%")
|
||||
db = db.Where("id IN (?)", subQuery)
|
||||
}
|
||||
|
||||
// 首先计算总数
|
||||
if err := db.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// 然后应用分页并获取数据
|
||||
// 然后应用排序、分页并获取数据
|
||||
if opts.OrderBy != "" {
|
||||
db = db.Order(opts.OrderBy)
|
||||
}
|
||||
offset := (page - 1) * pageSize
|
||||
if err := db.Preload("RawMaterialNutrients.RawMaterial").Offset(offset).Limit(pageSize).Find(&nutrients).Error; err != nil {
|
||||
return nil, 0, err
|
||||
|
||||
Reference in New Issue
Block a user