Anup
Anup

Reputation: 1712

How to set where clause dynamically in GORM

I will receive a map[string][]string. For each key in the map i want to add where clause like bellow.

inFilter := map[string][]string{"product_id": []string{"3", "69"}}
for key, value := range inFilter {
        filterQuerable = filterQuerable.Where("(?) IN (?)", key, value)
    }

it does not work. I tried bellow which also not works

filterQuerable = filterQuerable.Where("(?) IN (?)", "product_id", []string{"3", "69"})

Only bellow code works

filterQuerable = filterQuerable.Where("product_id IN (?)",  []string{"3", "69"})

Upvotes: 1

Views: 1009

Answers (2)

Alfro
Alfro

Reputation: 517

For this kind of where clause you don't even need the for loop if you already have a map defined.

This should work:

inFilter := map[string][]string{"product_id": []string{"3", "69"}}
filterQuerable.Where(inFilter)

Docs: https://gorm.io/docs/query.html#Struct-amp-Map-Conditions

Note: This has the added benefit that you can't inject SQL since gorm parses the map into columns/values.

Upvotes: 0

sberry
sberry

Reputation: 131978

I see the problem now. The ? is for values, not column names. If you can 100% trust the source of the inputs then a simple string replacement will work. If you are are allowing data from users then you should be very careful and validated / sanitize the column names.

This should work.

inFilter := map[string][]string{"product_id": []string{"3", "69"}}
for key, value := range inFilter {
   filterQuerable = filterQuerable.Where(key + " IN (?)", value)
}

Upvotes: 1

Related Questions