Skip to content
Advertisement

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"})

Advertisement

Answer

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)
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement