what can i to cancel the gorm where

59 Views Asked by At

i have a gorm query with many where,when i exec the final query, i want to cancel the previous where,what can i do i try to copy the base query,but it dose not work,

like this db.where().where().where().where()

when i finaly exec the query i want to cancel the third where,what can i do

query := resources.DB.Where("alarm_log.data_time >= ? and alarm_log.data_time < ? and alarm_policy.id = ? ", timeRangeInfo.StartTimeFormat, timeRangeInfo.EndTimeFormat, input.PolicyId)
if input.ObjectIds != nil && len(input.ObjectIds) != 0 {
    query.Where("object.id in ?", input.ObjectIds)
}
sql := alarm_log_base_list(query)
if err := sql.Where(searchQuery).
        Limit(input.PageSize).
        Offset((input.Current - 1) * input.PageSize).
        Find(&list).Error; err != nil && !errorx.Is(err, gorm.ErrRecordNotFound) {
        return nil, errors.WithMessagef(err, "Alarm_log_list's alarm_policy get list error")
    }
 if err := sql.Where("alarm_log.label = '1'").Limit(-1).Offset(-1).Count(&effectiveNum).Error; err != nil {
return nil, errors.WithMessagef(err, "Alarm_log_list's alarm_policy get  effectiveNum count error")

if err := sql.Where("alarm_log.label = '0'").Limit(-1).Offset(-1).Count(&uneffectiveNum).Error; err != nil {
    return nil, errors.WithMessagef(err, "Alarm_log_list's alarm_policy get  uneffectiveNum count error")
}

i want to cancel the where with label = 1

1

There are 1 best solutions below

0
ghanshyam On

you can modify your approach slightly. Instead of modifying the original query directly, you can create a new query based on the original one and adjust it as needed.

// Original query
query := resources.DB.Where("alarm_log.data_time >= ? and alarm_log.data_time < ? and alarm_policy.id = ? ", timeRangeInfo.StartTimeFormat, timeRangeInfo.EndTimeFormat, input.PolicyId)
if input.ObjectIds != nil && len(input.ObjectIds) != 0 {
    query = query.Where("object.id in ?", input.ObjectIds)
}

// Create a copy of the original query
sql := query

// Main query execution
if err := sql.Where(searchQuery).
    Limit(input.PageSize).
    Offset((input.Current - 1) * input.PageSize).
    Find(&list).Error; err != nil && !errorx.Is(err, gorm.ErrRecordNotFound) {
    return nil, errors.WithMessagef(err, "Alarm_log_list's alarm_policy get list error")
}

// Count query with 'label = '1''
if err := query.Where("alarm_log.label = '1'").Limit(-1).Offset(-1).Count(&effectiveNum).Error; err != nil {
    return nil, errors.WithMessagef(err, "Alarm_log_list's alarm_policy get  effectiveNum count error")
}

// Count query with 'label = '0''
if err := sql.Where("alarm_log.label = '0'").Limit(-1).Offset(-1).Count(&uneffectiveNum).Error; err != nil {
    return nil, errors.WithMessagef(err, "Alarm_log_list's alarm_policy get  uneffectiveNum count error")
}

We use sql for the main query execution and modify query for the count query with 'label = '1''.