本文介绍了如何使用xorm orm框架封装多字段复杂查询。通过定义请求数据结构,转换请求数据,并构建查询构建器,可以轻松实现复杂查询功能。

一、请求数据结构定义
使用JSON格式的请求数据,可以使用Go语言结构体表示:
type Request struct { Limit int Offset int Asc []string Desc []string And map[string]Condition Or map[string]Condition}type Condition struct { Cond string Value []interface{}}
二、请求数据转换及查询构建
createQueryBuilder 函数将JSON请求数据转换为可用于Xorm查询的对象:
func createQueryBuilder(req Request, tableName string) *xorm.Session { query := engine.Table(tableName) // engine 为已初始化的 xorm engine if req.Limit > 0 { query = query.Limit(req.Limit, req.Offset) } if len(req.Asc) > 0 { query = query.Asc(req.Asc...) } if len(req.Desc) > 0 { query = query.Desc(req.Desc...) } for field, cond := range req.And { query = addCondition(query, field, cond, true) } for field, cond := range req.Or { query = addCondition(query, field, cond, false) } return query}func addCondition(query *xorm.Session, field string, cond Condition, and bool) *xorm.Session { switch cond.Cond { case "gt": if and { query = query.And(field+" > ?", cond.Value[0]) } else { query = query.Or(field+" > ?", cond.Value[0]) } case "lt": if and { query = query.And(field+" < ?", cond.Value[0]) } else { query = query.Or(field+" 0 { if and { query = query.And(field+" IN (?)", cond.Value) } else { query = query.Or(field+" IN (?)", cond.Value) } } case "notin": if len(cond.Value) > 0 { if and { query = query.And(field+" NOT IN (?)", cond.Value) } else { query = query.Or(field+" NOT IN (?)", cond.Value) } } case "like": if len(cond.Value) == 1 { if and { query = query.And(field+" LIKE ?", "%"+cond.Value[0].(string)+"%") } else { query = query.Or(field+" LIKE ?", "%"+cond.Value[0].(string)+"%") } } case "notlike": if len(cond.Value) == 1 { if and { query = query.And(field+" NOT LIKE ?", "%"+cond.Value[0].(string)+"%") } else { query = query.Or(field+" NOT LIKE ?", "%"+cond.Value[0].(string)+"%") } } case "between": if len(cond.Value) == 2 { if and { query = query.And(field+" BETWEEN ? AND ?", cond.Value[0], cond.Value[1]) } else { query = query.Or(field+" BETWEEN ? AND ?", cond.Value[0], cond.Value[1]) } } } return query}
三、查询调用
QueryWithAndOr 函数使用构建器执行查询:
func QueryWithAndOr(req Request, tableName string) ([]interface{}, error) { var res []interface{} // 使用interface{} 适应多种数据类型 query := createQueryBuilder(req, tableName) err := query.Find(&res) if err != nil { return nil, err } return res, nil}
这段代码对原代码进行了改进,使其更健壮,并增加了对不同数据类型的支持。 注意,engine 需要预先初始化。 res 使用 []interface{} 来适应各种数据类型,需要根据实际情况进行类型断言。 LIKE 和 NOT LIKE 条件增加了对字符串类型的检查。 IN 和 NOT IN 条件使用了更简洁的写法。 Limit 的使用也更规范。 记住替换 TestTable 为你的实际表结构体。
请确保你的 import 语句包含 github.com/go-xorm/xorm。 这个改进后的代码更清晰、更易于维护,并且处理了更多潜在的错误情况。
以上就是如何使用Xorm ORM封装多字段复杂查询?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1384250.html
微信扫一扫
支付宝扫一扫