假设我有一个表 employments
和一个结构 Employment
type Employment struct {
ID int `json:"id"`
Created_at string `json:"created_at"`
Updated_at string `json:"updated_at"`
Education string `json:"education"`
Job string `json:"job"`
Position string `json:"position"`
Business_phone string `json:"business_phone"`
Next_payday string `json:"next_payday"`
Employment_type int `json:"employment_type"`
Income float64 `json:"income"`
Additional float64 `json:"additional"`
}
用户可以更新他们的employment
,问题是我不知道用户想更新哪些字段。
因此,我决定遍历输入结构以获取 非 nil 字段
以生成查询字符串,例如 UPDATE employments SET position=$1, income=$2 WHERE id=$3
这是我这次得到的
func FlexibleUpdate(table_name string, str interface{}, cond string, ret string) string {
query := "UPDATE " + table_name + " SET "
j := 0
m := structs.Map(str)
for i := range m {
if m[i] != "" && m[i] != 0 && m[i] != 0.0 && {
j++
query = query + strings.ToLower(i) + "=$" + strconv.Itoa(j) + ","
}
}
j++
// adding conditions
if cond != "" {
query = query[:len(query)-1] + " WHERE " + cond + "=$" + strconv.Itoa(j)
}
// return values
if ret != "" {
query = query + " RETURNING " + ret
}
return query
}
我不知道如何将输入值分配给 $1, $2, ...
以执行查询
database.DB.QueryRow(query_string, value_1, value_2, ...)
如果您有任何想法或其他解决方法,请告诉我。
最佳答案
只需将非 nil 值收集到一个 slice 中,然后在执行查询时将该 slice 与 ...
一起使用。
var values []interface{}
for i := range m {
if v := m[i]; v != "" && v != 0 && v != 0.0 && /* you're missing a condition here */{
j++
query = query + strings.ToLower(i) + "=$" + strconv.Itoa(j) + ","
values = append(values, v)
}
}
// ....
database.DB.QueryRow(query_string, values...)
关于postgresql - 使用 Postgres 的 Golang UPDATE 专栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45823566/