创建批次时插入一条记录

This commit is contained in:
2025-10-05 18:28:16 +08:00
parent 9c35372720
commit 2aa0f09079
9 changed files with 145 additions and 26 deletions

View File

@@ -67,16 +67,14 @@ const (
// PigBatchLog 记录了猪批次数量或状态的每一次变更
type PigBatchLog struct {
gorm.Model
PigBatchID uint `gorm:"not null;index;comment:关联的猪批次ID"`
ChangeType LogChangeType `gorm:"size:20;not null;comment:变更类型"`
ChangeCount int `gorm:"not null;comment:数量变化,负数表示减少"`
Reason string `gorm:"size:255;comment:变更原因描述"`
BeforeCount int `gorm:"not null;comment:变更前总数"`
AfterCount int `gorm:"not null;comment:变更后总数"`
BeforeSickCount int `gorm:"not null;comment:变更前病猪数"`
AfterSickCount int `gorm:"not null;comment:变更后病猪数"`
OperatorID uint `gorm:"comment:操作员ID"`
HappenedAt time.Time `gorm:"primaryKey;comment:事件发生时间"`
PigBatchID uint `gorm:"not null;index;comment:关联的猪批次ID"`
ChangeType LogChangeType `gorm:"size:20;not null;comment:变更类型"`
ChangeCount int `gorm:"not null;comment:数量变化,负数表示减少"`
Reason string `gorm:"size:255;comment:变更原因描述"`
BeforeCount int `gorm:"not null;comment:变更前总数"`
AfterCount int `gorm:"not null;comment:变更后总数"`
OperatorID uint `gorm:"comment:操作员ID"`
HappenedAt time.Time `gorm:"primaryKey;comment:事件发生时间"`
}
func (PigBatchLog) TableName() string {

View File

@@ -0,0 +1,27 @@
package repository
import (
"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
}
// 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
}

View File

@@ -8,6 +8,7 @@ import (
// PigBatchRepository 定义了与猪批次相关的数据库操作接口
type PigBatchRepository interface {
CreatePigBatch(batch *models.PigBatch) (*models.PigBatch, error)
CreatePigBatchTx(tx *gorm.DB, batch *models.PigBatch) (*models.PigBatch, error)
GetPigBatchByID(id uint) (*models.PigBatch, error)
GetPigBatchByIDTx(tx *gorm.DB, id uint) (*models.PigBatch, error)
// UpdatePigBatch 更新一个猪批次,返回更新后的批次、受影响的行数和错误
@@ -29,7 +30,12 @@ func NewGormPigBatchRepository(db *gorm.DB) PigBatchRepository {
// CreatePigBatch 创建一个新的猪批次
func (r *gormPigBatchRepository) CreatePigBatch(batch *models.PigBatch) (*models.PigBatch, error) {
if err := r.db.Create(batch).Error; err != nil {
return r.CreatePigBatchTx(r.db, batch)
}
// CreatePigBatchTx 在指定的事务中,创建一个新的猪批次
func (r *gormPigBatchRepository) CreatePigBatchTx(tx *gorm.DB, batch *models.PigBatch) (*models.PigBatch, error) {
if err := tx.Create(batch).Error; err != nil {
return nil, err
}
return batch, nil