dongpanbo4727 2016-12-04 15:42
浏览 63
已采纳

如何遍历结构的字段以进行查询过滤

I have a database where each row corresponds to a struct with the following fields

type item struct {
    ItemId *string `json:"item_id"`
    OwnerId *string `json:"owner_id"`
    Status *string `json:"status"`
    ... // many more
}

Inside the database, all fields are filled for all rows. Now I would like to have a function that takes an item object whose fields may not be filled as input and return a SQL query string. For example

func FindItems(filter item) string

The input item serves as a filter. The logic is as follows (in kind of python style)

query = `select * from item_table`
condition = ""
for field, value in filter:
    if value != nil:
        condition = " and " if condition else " where "
        condition += " field=value"
query += condition

How can I do this in go? Or is there a better way to do filter in go?

  • 写回答

1条回答 默认 最新

  • dongqiu9018 2016-12-04 18:13
    关注

    You can use reflect package to enumerate your structure fields and values:

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    type item struct {
        ItemID  *string `json:"item_id"`
        OwnerID *string `json:"owner_id"`
        Status  *string `json:"status"`
    }
    
    func FindItemsQuery(filter item) string {
        query := `select * from item_table`
        condition := ""
        val := reflect.ValueOf(filter)
        for i := 0; i < val.NumField(); i++ {
            valField := val.Field(i)
            if !valField.IsNil() {
                if condition != "" {
                    condition += " and "
                } else {
                    condition += " where "
                }
                condition += fmt.Sprintf("%s=%v", val.Type().Field(i).Tag.Get("json"), valField.Elem())
            }
        }
        return query + condition
    }
    
    func main() {
        itemID := "123"
        item := item{ItemID: &itemID}
        fmt.Println(FindItemsQuery(item)) // select * from item_table where item_id=123
    }
    

    Keep in mind that using additional json tags like json:"item_id,omitempty" will break your query. You should consider using custom structure tags to define the names of SQL fields.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条