删除设备时检查
This commit is contained in:
		@@ -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
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user