Gorm之查询条件

我在学习gorm的时候发现他有一个不好用的地方,我在使用map查询的条件的时候,只有“=”没有其他的运算符,这个让我有点用起来很不爽,也不很方便。我之前是学PHP的,PHP的laravel框架就提供了这个便捷,比如$condition[] = ["age",">",20],这种用起来很舒服,所以我仿照这个用法,编写了一个拼接查询的条件工具,具体的实现代码如下所示:

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
}

目前这种实现方法利用了map来实现,但是还有一种方法可以实现,仿照php的laravel框架实现形式利用切片的形式也是可以实现的,这种实现方法和这种类似,我就不实现了。

具体的用法如下所示:

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)

以上就是拼接sql条件的构建。

你可能感兴趣的:(Gorm之查询条件)