Last active
August 18, 2020 09:12
-
-
Save aloha1003/119c612044213388490459f550da9697 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//宣告搜尋條件 | |
search := map[string]interface{}{ | |
"columnA": 1, | |
"columnB >": 2, | |
"columnC <" : 3, | |
} | |
//宣告grom物件 | |
model =model.XXX{} | |
cond, vals, err := database.WhereBuild(search) | |
if err := db.Table("tableName").Where(cond, vals...).Find(&model).Error; err != nil { | |
// do something | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//WhereBuild sql build where | |
func WhereBuild(where map[string]interface{}) (whereSQL string, vals []interface{}, err error) { | |
for k, v := range where { | |
ks := strings.Split(k, " ") | |
if len(ks) > 2 { | |
return "", nil, fmt.Errorf("Error in query condition: %s. ", k) | |
} | |
if whereSQL != "" { | |
whereSQL += " AND " | |
} | |
strings.Join(ks, ",") | |
switch len(ks) { | |
case 1: | |
//fmt.Println(reflect.TypeOf(v)) | |
switch v := v.(type) { | |
case NullType: | |
if v == IsNotNull { | |
whereSQL += fmt.Sprint(k, " IS NOT NULL") | |
} else { | |
whereSQL += fmt.Sprint(k, " IS NULL") | |
} | |
default: | |
whereSQL += fmt.Sprint(k, "=?") | |
vals = append(vals, v) | |
} | |
break | |
case 2: | |
k = ks[0] | |
switch ks[1] { | |
case "=": | |
whereSQL += fmt.Sprint(k, "=?") | |
vals = append(vals, v) | |
break | |
case ">": | |
whereSQL += fmt.Sprint(k, ">?") | |
vals = append(vals, v) | |
break | |
case ">=": | |
whereSQL += fmt.Sprint(k, ">=?") | |
vals = append(vals, v) | |
break | |
case "<": | |
whereSQL += fmt.Sprint(k, "<?") | |
vals = append(vals, v) | |
break | |
case "<=": | |
whereSQL += fmt.Sprint(k, "<=?") | |
vals = append(vals, v) | |
break | |
case "!=": | |
whereSQL += fmt.Sprint(k, "!=?") | |
vals = append(vals, v) | |
break | |
case "<>": | |
whereSQL += fmt.Sprint(k, "!=?") | |
vals = append(vals, v) | |
break | |
case "in": | |
whereSQL += fmt.Sprint(k, " in (?)") | |
vals = append(vals, v) | |
break | |
case "like": | |
whereSQL += fmt.Sprint(k, " like ?") | |
vals = append(vals, v) | |
} | |
break | |
} | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment