47 lines
1.5 KiB
Go
47 lines
1.5 KiB
Go
|
|
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
|
|||
|
|
}
|