设备和区域主控删除时清除对应区域阈值告警或设备阈值告警任务
This commit is contained in:
@@ -47,8 +47,8 @@ type DeviceRepository interface {
|
||||
// GetDevicesByIDsTx 在指定事务中根据ID列表获取设备
|
||||
GetDevicesByIDsTx(ctx context.Context, tx *gorm.DB, ids []uint) ([]models.Device, error)
|
||||
|
||||
// IsDeviceInUse 检查设备是否被任何任务使用
|
||||
IsDeviceInUse(ctx context.Context, deviceID uint) (bool, error)
|
||||
// IsDeviceInUse 检查设备是否被任何任务使用,可以忽略指定任务类型
|
||||
IsDeviceInUse(ctx context.Context, deviceID uint, ignoredTaskTypes []models.TaskType) (bool, error)
|
||||
|
||||
// IsAreaControllerInUse 检查区域主控是否被任何设备使用
|
||||
IsAreaControllerInUse(ctx context.Context, areaControllerID uint) (bool, error)
|
||||
@@ -184,12 +184,22 @@ func (r *gormDeviceRepository) FindByAreaControllerAndPhysicalAddress(ctx contex
|
||||
return &device, nil
|
||||
}
|
||||
|
||||
// IsDeviceInUse 检查设备是否被任何任务使用
|
||||
func (r *gormDeviceRepository) IsDeviceInUse(ctx context.Context, deviceID uint) (bool, error) {
|
||||
// IsDeviceInUse 检查设备是否被任何任务使用,可以忽略指定任务类型
|
||||
func (r *gormDeviceRepository) IsDeviceInUse(ctx context.Context, deviceID uint, ignoredTaskTypes []models.TaskType) (bool, error) {
|
||||
repoCtx := logs.AddFuncName(ctx, r.ctx, "IsDeviceInUse")
|
||||
var count int64
|
||||
// 直接对 device_tasks 关联表进行 COUNT 操作,性能最高
|
||||
err := r.db.WithContext(repoCtx).Model(&models.DeviceTask{}).Where("device_id = ?", deviceID).Count(&count).Error
|
||||
|
||||
// 构建查询,需要 JOIN tasks 表来过滤 TaskType
|
||||
query := r.db.WithContext(repoCtx).
|
||||
Model(&models.DeviceTask{}).
|
||||
Joins("JOIN tasks ON tasks.id = device_tasks.task_id").
|
||||
Where("device_tasks.device_id = ?", deviceID)
|
||||
|
||||
if len(ignoredTaskTypes) > 0 {
|
||||
query = query.Where("tasks.type NOT IN (?)", ignoredTaskTypes)
|
||||
}
|
||||
|
||||
err := query.Count(&count).Error
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("查询设备任务关联失败: %w", err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user