From 0b0e6a8da5d327bb191a567867b5f419b9bd4d27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Fri, 9 Aug 2024 22:13:34 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8DIN/NOT=20IN=20=E6=9E=84?= =?UTF-8?q?=E5=BB=BA=E7=9A=84BUG?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- option.go | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/option.go b/option.go index e0bd1ee..a253d34 100644 --- a/option.go +++ b/option.go @@ -425,9 +425,9 @@ func optionToSql(o *Option) (sqlBuildResult string, bindValue []any) { } if reflect.TypeOf(fieldValue).Kind() == reflect.Slice { // 传入数组, in语句 - sqlBuildResultBlockList = append(sqlBuildResultBlockList, "`"+fieldName+"` in (?)") - byteData, _ := json.Marshal(fieldValue) - bindValue = append(bindValue, strings.TrimRight(strings.TrimLeft(string(byteData), "["), "]")) + placeholder, dataList := parseInSql(fieldValue) + sqlBuildResultBlockList = append(sqlBuildResultBlockList, "`"+fieldName+"` IN ("+placeholder+")") + bindValue = append(bindValue, dataList...) } else { sqlBuildResultBlockList = append(sqlBuildResultBlockList, "`"+fieldName+"` = ?") bindValue = append(bindValue, fieldValue) @@ -442,16 +442,16 @@ func optionToSql(o *Option) (sqlBuildResult string, bindValue []any) { // in 语句 // 传入数组, in语句 for fieldName, fieldValue := range o.In { - sqlBuildResultBlockList = append(sqlBuildResultBlockList, "`"+fieldName+"` in (?)") - byteData, _ := json.Marshal(fieldValue) - bindValue = append(bindValue, strings.TrimRight(strings.TrimLeft(string(byteData), "["), "]")) + placeholder, dataList := parseInSql(fieldValue) + sqlBuildResultBlockList = append(sqlBuildResultBlockList, "`"+fieldName+"` IN ("+placeholder+")") + bindValue = append(bindValue, dataList...) } // not in 语句 for fieldName, fieldValue := range o.NotIn { - sqlBuildResultBlockList = append(sqlBuildResultBlockList, "`"+fieldName+"` NOT IN (?)") - byteData, _ := json.Marshal(fieldValue) - bindValue = append(bindValue, strings.TrimRight(strings.TrimLeft(string(byteData), "["), "]")) + placeholder, dataList := parseInSql(fieldValue) + sqlBuildResultBlockList = append(sqlBuildResultBlockList, "`"+fieldName+"` NOT IN ("+placeholder+")") + bindValue = append(bindValue, dataList...) } // like 语句 @@ -489,3 +489,22 @@ func optionToSql(o *Option) (sqlBuildResult string, bindValue []any) { } return } + +// parseInSql 解析in语句需要绑定占位符以及数据 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 22:07 2024/8/9 +func parseInSql(fieldValue any) (string, []any) { + byteData, _ := json.Marshal(fieldValue) + var dataList []any + decoder := json.NewDecoder(strings.NewReader(string(byteData))) + decoder.UseNumber() + _ = decoder.Decode(&dataList) + // 生成占位符 + placeholderList := make([]string, 0) + for i := 0; i < len(dataList); i++ { + placeholderList = append(placeholderList, "?") + } + return strings.Join(placeholderList, ","), dataList +}