添加区域主控相关路由
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -8,7 +10,11 @@ import (
|
||||
// AreaControllerRepository 定义了对 AreaController 模型的数据库操作接口
|
||||
type AreaControllerRepository interface {
|
||||
FindByID(id uint) (*models.AreaController, error)
|
||||
FindByNetworkID(networkID string) (*models.AreaController, error) // New method
|
||||
FindByNetworkID(networkID string) (*models.AreaController, error)
|
||||
Create(ac *models.AreaController) error
|
||||
ListAll() ([]*models.AreaController, error)
|
||||
Update(ac *models.AreaController) error
|
||||
Delete(id uint) error
|
||||
}
|
||||
|
||||
// gormAreaControllerRepository 是 AreaControllerRepository 的 GORM 实现。
|
||||
@@ -21,6 +27,48 @@ func NewGormAreaControllerRepository(db *gorm.DB) AreaControllerRepository {
|
||||
return &gormAreaControllerRepository{db: db}
|
||||
}
|
||||
|
||||
// Create 创建一个新的 AreaController 记录。
|
||||
func (r *gormAreaControllerRepository) Create(ac *models.AreaController) error {
|
||||
return r.db.Create(ac).Error
|
||||
}
|
||||
|
||||
// ListAll 返回所有 AreaController 的列表。
|
||||
func (r *gormAreaControllerRepository) ListAll() ([]*models.AreaController, error) {
|
||||
var areaControllers []*models.AreaController
|
||||
if err := r.db.Find(&areaControllers).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return areaControllers, nil
|
||||
}
|
||||
|
||||
// Update 更新一个已存在的 AreaController 记录。
|
||||
func (r *gormAreaControllerRepository) Update(ac *models.AreaController) error {
|
||||
return r.db.Save(ac).Error
|
||||
}
|
||||
|
||||
// Delete 删除一个 AreaController 记录。
|
||||
// 在删除前会检查是否有设备关联到该主控,如果有,则不允许删除。
|
||||
func (r *gormAreaControllerRepository) Delete(id uint) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
// 检查是否有设备关联到这个区域主控
|
||||
var count int64
|
||||
if err := tx.Model(&models.Device{}).Where("area_controller_id = ?", id).Count(&count).Error; err != nil {
|
||||
return fmt.Errorf("检查关联设备失败: %w", err)
|
||||
}
|
||||
|
||||
if count > 0 {
|
||||
return fmt.Errorf("无法删除区域主控,因为仍有 %d 个设备关联到它", count)
|
||||
}
|
||||
|
||||
// 如果没有关联设备,则执行删除操作
|
||||
if err := tx.Delete(&models.AreaController{}, id).Error; err != nil {
|
||||
return fmt.Errorf("删除区域主控失败: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// FindByID 通过 ID 查找一个 AreaController。
|
||||
func (r *gormAreaControllerRepository) FindByID(id uint) (*models.AreaController, error) {
|
||||
var areaController models.AreaController
|
||||
|
||||
Reference in New Issue
Block a user