删除设备时检查

This commit is contained in:
2025-11-03 16:46:23 +08:00
parent 8669dcd9b0
commit f569876225
5 changed files with 86 additions and 7 deletions

View File

@@ -43,6 +43,9 @@ type DeviceRepository interface {
// GetDevicesByIDsTx 在指定事务中根据ID列表获取设备
GetDevicesByIDsTx(tx *gorm.DB, ids []uint) ([]models.Device, error)
// IsDeviceInUse 检查设备是否被任何任务使用
IsDeviceInUse(deviceID uint) (bool, error)
}
// gormDeviceRepository 是 DeviceRepository 的 GORM 实现
@@ -161,3 +164,14 @@ func (r *gormDeviceRepository) FindByAreaControllerAndPhysicalAddress(areaContro
}
return &device, nil
}
// IsDeviceInUse 检查设备是否被任何任务使用
func (r *gormDeviceRepository) IsDeviceInUse(deviceID uint) (bool, error) {
var count int64
// 直接对 device_tasks 关联表进行 COUNT 操作,性能最高
err := r.db.Model(&models.DeviceTask{}).Where("device_id = ?", deviceID).Count(&count).Error
if err != nil {
return false, fmt.Errorf("查询设备任务关联失败: %w", err)
}
return count > 0, nil
}