56 lines
2.2 KiB
Go
56 lines
2.2 KiB
Go
package repository
|
|
|
|
import (
|
|
"time" // 引入 time 包
|
|
|
|
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// PigBatchLogRepository 定义了与猪批次日志相关的数据库操作接口。
|
|
type PigBatchLogRepository interface {
|
|
// Create 在指定的事务中创建一条新的猪批次日志。
|
|
Create(tx *gorm.DB, log *models.PigBatchLog) error
|
|
|
|
// GetLogsByBatchIDAndDateRangeTx 在指定的事务中,获取指定批次在特定时间范围内的所有日志记录。
|
|
GetLogsByBatchIDAndDateRangeTx(tx *gorm.DB, batchID uint, startDate, endDate time.Time) ([]*models.PigBatchLog, error)
|
|
|
|
// GetLastLogByBatchIDTx 在指定的事务中,获取某批次的最后一条日志记录。
|
|
GetLastLogByBatchIDTx(tx *gorm.DB, batchID uint) (*models.PigBatchLog, error)
|
|
}
|
|
|
|
// gormPigBatchLogRepository 是 PigBatchLogRepository 的 GORM 实现。
|
|
type gormPigBatchLogRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
// NewGormPigBatchLogRepository 创建一个新的 PigBatchLogRepository 实例。
|
|
func NewGormPigBatchLogRepository(db *gorm.DB) PigBatchLogRepository {
|
|
return &gormPigBatchLogRepository{db: db}
|
|
}
|
|
|
|
// Create 实现了创建猪批次日志的逻辑。
|
|
func (r *gormPigBatchLogRepository) Create(tx *gorm.DB, log *models.PigBatchLog) error {
|
|
return tx.Create(log).Error
|
|
}
|
|
|
|
// GetLogsByBatchIDAndDateRangeTx 实现了在指定的事务中,获取指定批次在特定时间范围内的所有日志记录的逻辑。
|
|
func (r *gormPigBatchLogRepository) GetLogsByBatchIDAndDateRangeTx(tx *gorm.DB, batchID uint, startDate, endDate time.Time) ([]*models.PigBatchLog, error) {
|
|
var logs []*models.PigBatchLog
|
|
err := tx.Where("pig_batch_id = ? AND created_at >= ? AND created_at <= ?", batchID, startDate, endDate).Find(&logs).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return logs, nil
|
|
}
|
|
|
|
// GetLastLogByBatchIDTx 实现了在指定的事务中,获取某批次的最后一条日志记录的逻辑。
|
|
func (r *gormPigBatchLogRepository) GetLastLogByBatchIDTx(tx *gorm.DB, batchID uint) (*models.PigBatchLog, error) {
|
|
var log models.PigBatchLog
|
|
err := tx.Where("pig_batch_id = ?", batchID).Order("id DESC").First(&log).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &log, nil
|
|
}
|