gorm链式操作:
Method Chaining,Gorm 实现了链式操作接口,所以你可以把代码写成这样:
// 创建一个查询 tx := db.Where("name = ?", "jinzhu") // 添加更多条件 if someCondition { tx = tx.Where("age = ?", 20) } else { tx = tx.Where("age = ?", 30) } if yetAnotherCondition { tx = tx.Where("active = ?", 1) }
var db *gorm.DB // 已经进行了db的初始化操作,db为全局变量 func getUsers(c *gin.Context) { users := make([]User, 0) Db := db if age, isExist := c.GetQuery("age"); isExist == true { ageInt, _ := strconv.Atoi(age) Db = Db.Where("age = ?", ageInt) } if num, isExist := c.GetQuery("num"); isExist == true { numInt, _ := strconv.Atoi(num) Db = Db.Where("num = ?", numInt) } if name, isExist := c.GetQuery("name"); isExist == true { Db = Db.Where("name = ?", name) } if err := Db.Find(&users).Error; err != nil { fmt.Println(err.Error()) } c.JSON(http.StatusOK, gin.H{ "data": users, }) }
这里需要注意一个细节,首先将全局的db变量赋值给了Db,如果用db直接进行操作,那一系列的赋值语句将会影响db的地址,影响后续的数据库操作.
Db := db
https://www.jb51.net/article/202475.htm
类似 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条件的构建。
链接:https://www.jianshu.com/p/09eea18e33c1/
标签:Db,fmt,db,whereSql,golang,age,values,使用,gorm From: https://www.cnblogs.com/youxin/p/16945620.html