英文:
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("LOWER(name) LIKE LOWER(?)", fmt.Sprintf("%%%s%%", nameSearch))
Of course, you can just use "%" + nameSearch + "%"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论