Gorm组装多条件查询

技术 · 2022-08-17 · 132 人浏览

使用ma实现

func BuildCondition(where map[string]interface{}) (whereSql string,
    values []interface{}, err error) {
    for key, value := range where {
        conditionKey := strings.Split(key, " ")
        if len(conditionKey) > 2 {
            return "", nil, fmt.Errorf("" +
                "map构建的条件格式不对,类似于'age >'")
        }
        if whereSql != "" {
            whereSql += " AND "
        }
        switch len(conditionKey) {
        case 1:
            whereSql += fmt.Sprint(conditionKey[0], " = ?")
            values = append(values, value)
            break
        case 2:
            field := conditionKey[0]
            switch conditionKey[1] {
            case "=":
                whereSql += fmt.Sprint(field, " = ?")
                values = append(values, value)
                break
            case ">":
                whereSql += fmt.Sprint(field, " > ?")
                values = append(values, value)
                break
            case ">=":
                whereSql += fmt.Sprint(field, " >= ?")
                values = append(values, value)
                break
            case "<":
                whereSql += fmt.Sprint(field, " < ?")
                values = append(values, value)
                break
            case "<=":
                whereSql += fmt.Sprint(field, " <= ?")
                values = append(values, value)
                break
            case "in":
                whereSql += fmt.Sprint(field, " in (?)")
                values = append(values, value)
                break
            case "like":
                whereSql += fmt.Sprint(field, " like ?")
                values = append(values, value)
                break
            case "<>":
                whereSql += fmt.Sprint(field, " != ?")
                values = append(values, value)
                break
            case "!=":
                whereSql += fmt.Sprint(field, " != ?")
                values = append(values, value)
                break
            }
            break
        }
    }
    return
}

用法

conditionString, values, _ := tool.BuildCondition(map[string]interface{}{
        "itemNO":        "02WZ05133",
        "itemName like": "%22220",
        "id in":         []int{20, 19, 30},
        "num !=" : 20,
    })
var student model.Student
db.where(conditionString,values).Find(&student)
豫ICP备17047052号-1