This commit is contained in:
Yun
2023-12-27 19:10:09 +08:00
commit d6f5d1a4e6
3 changed files with 114 additions and 0 deletions
+38
View File
@@ -0,0 +1,38 @@
package gormx
import (
"context"
"fmt"
"gorm.io/gorm"
)
// 根据map组装gorm的where
func BuildWhere(ctx context.Context, m *gorm.DB, where map[string]interface{}) (*gorm.DB, error) {
for key, val := range where {
switch val.(type) {
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
m = m.Where(fmt.Sprintf("%s = ?", key), val)
case string:
m = m.Where(fmt.Sprintf("%s = ?", key), val)
case float32, float64:
m = m.Where(fmt.Sprintf("%s = ?", key), val)
case bool:
m = m.Where(fmt.Sprintf("%s = ?", key), val)
case []int, []int8, []int16, []int32, []int64, []uint, []uint8, []uint16, []uint32, []uint64:
m = m.Where(fmt.Sprintf("%s in (?)", key), val)
case []string:
m = m.Where(fmt.Sprintf("%s in (?)", key), val)
case []float32, []float64:
m = m.Where(fmt.Sprintf("%s in (?)", key), val)
case []bool:
m = m.Where(fmt.Sprintf("%s in (?)", key), val)
case []interface{}:
m = m.Where(fmt.Sprintf("%s in (?)", key), val)
default:
// byte,rune,any,nil
return nil, fmt.Errorf("unknown type:%+v %T", val, val)
}
}
return m, nil
}