简体   繁体   English

使用gorm的postgres中的“$ 1”或附近的golang语法错误

[英]golang syntax error at or near "$1" in postgres using gorm

I am trying to find multiple users based on their name.我试图根据他们的名字找到多个用户。 I am using gorm as follow:我正在使用gorm如下:

err := db.Where("username IN ?", []string{"name1", "name2"}).Find(&users).Error

But the generated query is:但生成的查询是:

SELECT * FROM "users_customer"."user" WHERE (username IN 'name1','name2')

when the correct query should be:当正确的查询应该是:

SELECT * FROM "users_customer"."user" WHERE username IN ('name1','name2')

So the error pq: syntax error at or near "$1" is thrown.因此错误pq: syntax error at or near "$1"被抛出。 I use the same syntax as stated in the doc, which is db.Where("name IN?", []string{"jinzhu", "jinzhu 2"}).Find(&users) but don't know why in my case it doesn't work.我使用与文档中所述相同的语法,即db.Where("name IN?", []string{"jinzhu", "jinzhu 2"}).Find(&users)但不知道为什么在我的如果它不起作用。

Gorm by default ad ' this at each side and it does not add brackets () . Gorm默认情况下在每一侧都添加' this 并且它不添加括号()

You should add it manually like this:您应该像这样手动添加它:

    names := []string{"name1", "name2"}

    commaSep := "'" + strings.Join(names, "', '") + "'"
    err := db.Where("username IN (?)", commaSep).Find(&users).Error

You can run it here: https://go.dev/play/p/ox3H2gL1yek你可以在这里运行它: https://go.dev/play/p/ox3H2gL1yek

OR或者

err := db.Where("username IN (?)", []string{"name1", "name2"}).Find(&users).Error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM