golang-gorm中使用like的where语句

huangapple go评论133阅读模式
英文:

golang-gorm .where with like

问题

我找不到类似的东西,但它与这个(不是使用golang)链接非常相似。

DB.Where(like(client))

我应该创建一个返回SQL查询的函数吗?

编辑:我指的是使用结构体而不是字符串查询。

英文:

i couldn't find any thing like this but it is exactly like (not in golang ) this

DB.Where(like(client))

should i make a function that return the sql query

edit : i meant using a struct not a string query

答案1

得分: 4

从GORM文档中,例如:

db.Where("name LIKE ?", "%jin%")

https://gorm.io/docs/query.html#Conditions

英文:

From the GORM docs e.g.

db.Where("name LIKE ?", "%jin%")

https://gorm.io/docs/query.html#Conditions

答案2

得分: 0

我写了一个返回SQL查询的函数:

func like(s interface{}) string{
    val := reflect.ValueOf(s)
    var name string = val.Type().Field(0).Tag.Get("json")
    var value interface{}
    var res string
    for i := 0; i < val.NumField();i++{
        name = val.Type().Field(i).Tag.Get("form")
        value = val.Field(i).Interface()
        if name != "-" && name != "" && value != ""{
            if res != ""{
                res += fmt.Sprintf("AND %s LIKE \"%%%v%%\" ",name,value)
            } else {
                res += fmt.Sprintf("%s LIKE \"%%%v%%\" ",name,value)
            }
        }
    }
    return res
}

对于代码混乱的问题,我很抱歉。

编辑:该函数的问题在于它容易受到SQL注入攻击。我使用了bindQuery(),但注入仍然有效。请给我一个解决方案。
gorm文档:https://gorm.io/docs/sql_builder.html#Named-Argument

英文:

i wrote a function that returns a SQL query :

func like(s interface{}) string{
	val := reflect.ValueOf(s)
	var name string = val.Type().Field(0).Tag.Get(&quot;json&quot;)
	var value interface{}
	var res string
	for i := 0; i &lt; val.NumField();i++{
		name = val.Type().Field(i).Tag.Get(&quot;form&quot;)
		value = val.Field(i).Interface()
		if name != &quot;-&quot; &amp;&amp; name != &quot;&quot; &amp;&amp; value != &quot;&quot;{
			if res != &quot;&quot;{
				res += fmt.Sprintf(&quot;AND %s LIKE \&quot;%%%v%%\&quot; &quot;,name,value)
			} else {
				res += fmt.Sprintf(&quot;%s LIKE \&quot;%%%v%%\&quot; &quot;,name,value)
			}
		}
	}
	return res
}

sorry for the messy code

edit : the problem with the function is that it is vulnerable against
SQL injections i use bindQuery() and the injection worked plz give me a solution
gorm doc : https://gorm.io/docs/sql_builder.html#Named-Argument

huangapple
  • 本文由 发表于 2022年7月21日 05:02:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/73058090.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定