ListWeighingBatches
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -17,6 +19,17 @@ type PigBatchRepository interface {
|
||||
DeletePigBatch(id uint) (int64, error)
|
||||
DeletePigBatchTx(tx *gorm.DB, id uint) (int64, error)
|
||||
ListPigBatches(isActive *bool) ([]*models.PigBatch, error)
|
||||
|
||||
// ListWeighingBatches 支持分页和过滤的批次称重列表查询
|
||||
ListWeighingBatches(opts WeighingBatchListOptions, page, pageSize int) ([]models.WeighingBatch, int64, error)
|
||||
}
|
||||
|
||||
// WeighingBatchListOptions 定义了查询批次称重记录时的可选参数
|
||||
type WeighingBatchListOptions struct {
|
||||
PigBatchID *uint
|
||||
StartTime *time.Time // 基于 weighing_time 字段
|
||||
EndTime *time.Time // 基于 weighing_time 字段
|
||||
OrderBy string // 例如 "weighing_time asc"
|
||||
}
|
||||
|
||||
// gormPigBatchRepository 是 PigBatchRepository 的 GORM 实现
|
||||
@@ -100,3 +113,40 @@ func (r *gormPigBatchRepository) GetPigBatchByIDTx(tx *gorm.DB, id uint) (*model
|
||||
}
|
||||
return &batch, nil
|
||||
}
|
||||
|
||||
// ListWeighingBatches 实现了分页和过滤查询批次称重记录的功能
|
||||
func (r *gormPigBatchRepository) ListWeighingBatches(opts WeighingBatchListOptions, page, pageSize int) ([]models.WeighingBatch, int64, error) {
|
||||
if page <= 0 || pageSize <= 0 {
|
||||
return nil, 0, ErrInvalidPagination
|
||||
}
|
||||
|
||||
var results []models.WeighingBatch
|
||||
var total int64
|
||||
|
||||
query := r.db.Model(&models.WeighingBatch{})
|
||||
|
||||
if opts.PigBatchID != nil {
|
||||
query = query.Where("pig_batch_id = ?", *opts.PigBatchID)
|
||||
}
|
||||
if opts.StartTime != nil {
|
||||
query = query.Where("weighing_time >= ?", *opts.StartTime)
|
||||
}
|
||||
if opts.EndTime != nil {
|
||||
query = query.Where("weighing_time <= ?", *opts.EndTime)
|
||||
}
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
orderBy := "weighing_time DESC"
|
||||
if opts.OrderBy != "" {
|
||||
orderBy = opts.OrderBy
|
||||
}
|
||||
query = query.Order(orderBy)
|
||||
|
||||
offset := (page - 1) * pageSize
|
||||
err := query.Limit(pageSize).Offset(offset).Find(&results).Error
|
||||
|
||||
return results, total, err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user