1

I am trying to find multiple users based on their name. I am using gorm as follow:

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. 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.

2
  • 2
    Did you try IN (?) inside your String? Commented Dec 14, 2021 at 11:42
  • @a_horse_with_no_name. problem solved. Thank you. Commented Dec 14, 2021 at 12:25

1 Answer 1

2

Gorm by default ad ' this at each side and it does not add brackets ().

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

OR

err := db.Where("username IN (?)", []string{"name1", "name2"}).Find(&users).Error
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.