多查询条件自由组合
多条件筛选的功能还是很常见的,每种筛选条件都可选可不选,这样就有n(n-1)/2种自由组合的方式,如果每种条件是最小单元,就像搭积木一样把他们任意组合,那么代码就会变得更灵活可复用
- 将查询条件作为最小单元
GetRdsSlowLogOption为函数类型,参数和返回类型均为指数型gorm种的DB对象,此对象绑定了所有操作数据库的方法
WhereFilterRdsSlowLogPlatform函数返回GetRdsSlowLogOption类型的函数,该函数返回绑定了以platform字段为条件的*DB对象
type GetRdsSlowLogOption func(tx *gorm.DB) *gorm.DB
func WhereFilterRdsSlowLogPlatform(platform []string) GetRdsSlowLogOption {
return func(tx *gorm.DB) *gorm.DB {
return tx.Where("platform.platform in (?)", platform)
}
}
- 建设自由组合查询条件的公共方法
args参数为前端传参,绑定initFilter方法来初始化查询条件并追加到列表getOpts
func (args *RdsSlowLogInfoRequest) initFilter() {
getOpts := []db_meta_data.GetRdsSlowLogOption{}
if len(args.Department) > 0 {
getOpts = append(getOpts, db_meta_data.WhereFilterRdsSlowLogPlatform(args.Department))
}
if len(args.BusLine) > 0 {
getOpts = append(getOpts, db_meta_data.WhereFilterRdsSlowLogBusLine(args.BusLine))
}
...//任何条件
args.Filter = getOpts
}
- 任何需要有查询条件的第方均可以调用args.initFilter() 来获取需要的组合条件
- 然后应用这些查询条件
func WhereSlowLogInfoOpt(limit int, offset int, opts []GetRdsSlowLogOption) *gorm.DB {
opts = append(opts, WhereNotFilterRdsSlowLogTag("%SLOW_IGNORE%")) //过滤掉正常sql)
tx := dbClient.Model(&RdsSlowInfo{}).Select("rds_slow_info.*,db_meta.bus_line,platform.platform").
Joins("join db_meta on rds_slow_info.db_name=db_meta.cluster_name").
Joins("left join platform on db_meta.bus_line=platform.psm_tree")
for i := range opts {
tx = opts[i](tx)
}
if limit > 0 {
tx = tx.Limit(limit)
if offset > 0 {
tx = tx.Offset(offset)
}
}
return tx
}
gorm 踩坑记录
对于left join 后的null值后自动按照上一行有值的进行填充,解决方法是用ifnull函数将可能出现null值的列转化为空字符串,比如ifnull(col,‘’)