拓展接口响应
This commit is contained in:
@@ -11,12 +11,19 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// RawMaterialListOptions 定义了查询原料列表时的筛选条件
|
||||
type RawMaterialListOptions struct {
|
||||
Name *string
|
||||
NutrientName *string
|
||||
OrderBy string
|
||||
}
|
||||
|
||||
// RawMaterialRepository 定义了与原料相关的数据库操作接口
|
||||
type RawMaterialRepository interface {
|
||||
CreateRawMaterial(ctx context.Context, rawMaterial *models.RawMaterial) error
|
||||
GetRawMaterialByID(ctx context.Context, id uint32) (*models.RawMaterial, error)
|
||||
GetRawMaterialByName(ctx context.Context, name string) (*models.RawMaterial, error)
|
||||
ListRawMaterials(ctx context.Context, page, pageSize int) ([]models.RawMaterial, int64, error)
|
||||
ListRawMaterials(ctx context.Context, opts RawMaterialListOptions, page, pageSize int) ([]models.RawMaterial, int64, error)
|
||||
UpdateRawMaterial(ctx context.Context, rawMaterial *models.RawMaterial) error
|
||||
DeleteRawMaterial(ctx context.Context, id uint32) error
|
||||
|
||||
@@ -64,20 +71,38 @@ func (r *gormRawMaterialRepository) GetRawMaterialByName(ctx context.Context, na
|
||||
return &rawMaterial, nil
|
||||
}
|
||||
|
||||
// ListRawMaterials 列出所有原料(分页),并预加载关联的营养素信息
|
||||
func (r *gormRawMaterialRepository) ListRawMaterials(ctx context.Context, page, pageSize int) ([]models.RawMaterial, int64, error) {
|
||||
// ListRawMaterials 列出所有原料(分页),支持按名称和营养名称筛选
|
||||
func (r *gormRawMaterialRepository) ListRawMaterials(ctx context.Context, opts RawMaterialListOptions, page, pageSize int) ([]models.RawMaterial, int64, error) {
|
||||
repoCtx := logs.AddFuncName(ctx, r.ctx, "ListRawMaterials")
|
||||
var rawMaterials []models.RawMaterial
|
||||
var total int64
|
||||
|
||||
db := r.db.WithContext(repoCtx).Model(&models.RawMaterial{})
|
||||
|
||||
// 应用筛选条件
|
||||
if opts.Name != nil && *opts.Name != "" {
|
||||
db = db.Where("name LIKE ?", "%"+*opts.Name+"%")
|
||||
}
|
||||
|
||||
// 如果传入了营养名称,则使用子查询进行筛选
|
||||
if opts.NutrientName != nil && *opts.NutrientName != "" {
|
||||
// 子查询:从 raw_material_nutrients 和 nutrients 表中找到所有包含该营养的 raw_material_id
|
||||
subQuery := r.db.Model(&models.RawMaterialNutrient{}).
|
||||
Select("raw_material_id").
|
||||
Joins("JOIN nutrients ON nutrients.id = raw_material_nutrients.nutrient_id").
|
||||
Where("nutrients.name LIKE ?", "%"+*opts.NutrientName+"%")
|
||||
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.Nutrient").Offset(offset).Limit(pageSize).Find(&rawMaterials).Error; err != nil {
|
||||
return nil, 0, err
|
||||
|
||||
Reference in New Issue
Block a user