Gorm查询格式化与`%`不兼容 – “期望0个参数,实际得到1个”

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

Gorm query formatting breaking with `%` - "expected 0 arguments, got 1"

问题

我遇到了一个错误,错误信息是“期望0个参数,但实际得到了1个”,这是在使用以下代码查询PostgreSQL时出现的:

db = db.Where("LOWER(name) LIKE LOWER('%?%')", nameSearch)

当我像下面这样硬编码数值时,它可以正常工作:

db = db.Where("LOWER(name) LIKE LOWER('%some-value%')")

有人能发现我的问题吗?我有很多类似格式的where条件可以正常工作,但是这个多了一个百分号(%)就出错了。

英文:

I am getting the error "expected 0 arguments, got 1" querying postgres with the following line:

db = db.Where("LOWER(name) LIKE LOWER('%?%')", nameSearch)

Which works when I hard code values into it like so:

db = db.Where("LOWER(name) LIKE LOWER('%some-value%')")

Can anyone spot my issue here as I have many where conditions similarly formatted that work but this one, with the extra % is breaking.

答案1

得分: 2

在快速查看文档后,似乎你应该将通配符添加到nameSearch变量中:如此处所示

> db.Where("name LIKE ?", "%jin%").Find(&users)<br>
> // SELECT * FROM users WHERE name LIKE '%jin%';

所以代码应该是:

db.Where("LOWER(name) LIKE LOWER(?)", fmt.Sprintf("%%%s%%", nameSearch))

当然,你也可以直接使用"%"+nameSearch+"%"

英文:

After a quick look at the docs, it seems like you should add the wildcards to the nameSearch variable: as shown here

> db.Where("name LIKE ?", "%jin%").Find(&users)<br>
> // SELECT * FROM users WHERE name LIKE '%jin%';

So that would be:

db.Where(&quot;LOWER(name) LIKE LOWER(?)&quot;, fmt.Sprintf(&quot;%%%s%%&quot;, nameSearch))

Of course, you can just use &quot;%&quot; + nameSearch + &quot;%&quot;

huangapple
  • 本文由 发表于 2022年6月13日 17:19:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/72600456.html
匿名

发表评论

匿名网友

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

确定