猪群管理聚合服务 增加调栏管理

This commit is contained in:
2025-10-05 17:30:39 +08:00
parent 6d080d250d
commit 01327eb8d2
10 changed files with 350 additions and 33 deletions

View File

@@ -0,0 +1,46 @@
package repository
import (
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
"gorm.io/gorm"
)
// PenRepository 定义了与猪栏模型相关的数据库操作接口。
type PenRepository interface {
GetPenByIDTx(tx *gorm.DB, penID uint) (*models.Pen, error)
GetPensByBatchIDTx(tx *gorm.DB, batchID uint) ([]*models.Pen, error)
UpdatePenFieldsTx(tx *gorm.DB, penID uint, updates map[string]interface{}) error
}
// penRepository 是 PenRepository 接口的 gorm 实现。
type penRepository struct {
db *gorm.DB
}
// NewPenRepository 创建一个新的 PenRepository 实例。
func NewPenRepository(db *gorm.DB) PenRepository {
return &penRepository{db: db}
}
// GetPenByIDTx 在指定的事务中通过ID获取单个猪栏信息。
func (r *penRepository) GetPenByIDTx(tx *gorm.DB, penID uint) (*models.Pen, error) {
var pen models.Pen
if err := tx.First(&pen, penID).Error; err != nil {
return nil, err
}
return &pen, nil
}
// GetPensByBatchIDTx 在指定的事务中,获取一个猪群当前关联的所有猪栏。
func (r *penRepository) GetPensByBatchIDTx(tx *gorm.DB, batchID uint) ([]*models.Pen, error) {
var pens []*models.Pen
if err := tx.Where("pig_batch_id = ?", batchID).Find(&pens).Error; err != nil {
return nil, err
}
return pens, nil
}
// UpdatePenFieldsTx 在指定的事务中,更新一个猪栏的指定字段。
func (r *penRepository) UpdatePenFieldsTx(tx *gorm.DB, penID uint, updates map[string]interface{}) error {
return tx.Model(&models.Pen{}).Where("id = ?", penID).Updates(updates).Error
}

View File

@@ -9,6 +9,7 @@ import (
type PigBatchRepository interface {
CreatePigBatch(batch *models.PigBatch) (*models.PigBatch, error)
GetPigBatchByID(id uint) (*models.PigBatch, error)
GetPigBatchByIDTx(tx *gorm.DB, id uint) (*models.PigBatch, error)
// UpdatePigBatch 更新一个猪批次,返回更新后的批次、受影响的行数和错误
UpdatePigBatch(batch *models.PigBatch) (*models.PigBatch, int64, error)
// DeletePigBatch 根据ID删除一个猪批次返回受影响的行数和错误
@@ -83,3 +84,12 @@ func (r *gormPigBatchRepository) ListPigBatches(isActive *bool) ([]*models.PigBa
}
return batches, nil
}
// GetPigBatchByIDTx 在指定的事务中通过ID获取单个猪批次
func (r *gormPigBatchRepository) GetPigBatchByIDTx(tx *gorm.DB, id uint) (*models.PigBatch, error) {
var batch models.PigBatch
if err := tx.First(&batch, id).Error; err != nil {
return nil, err
}
return &batch, nil
}