当前位置: 首页 > 工具软件 > Go GORM > 使用案例 >

golang gorm查询任意字段的组装方法

池宸
2023-12-01

查询指定未知长度字段的汇总方法

package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"log"
	"strings"
)

type FilterDo struct {
}

type ScanFields interface {
	IsScanField() bool
}

type Summary struct {
	Num1 int `json:"num1"` // num1
	Num2 int `json:"num2"` // num2
	Num3 int `json:"num3"` // num3
	Num4 int `json:"num4"` // num4
}

func (Summary) IsScanField() bool {
	return true
}

var db *gorm.DB

func GetDB() *gorm.DB {
	return db
}

type TableMember struct {
}

func ListCond(filter *FilterDo) (whereSql string, params []interface{}) {
	return
}

// SumFields gorm 实现指定查询任意字段
func SumFields(filter *FilterDo, results ScanFields, fields map[string]string) (err error) {
	if len(fields) == 0 {
		return
	}

	alias := make([]string, 0, len(fields))
	names := make([]string, 0, len(fields)+1)
	names = append(names, "m.id")
	for k, v := range fields {
		alias = append(alias, fmt.Sprintf("sum(%s) %s", strings.ReplaceAll(k, ",", "+"), v))
		if v != "id" {
			names = append(names, fmt.Sprintf("m.%s", strings.ReplaceAll(k, ",", ",m.")))
		}
	}

	condition, params := ListCond(filter)
	subQuery := GetDB().Model(&TableMember{}).
		Select("distinct "+strings.Join(names, ",")).
		Table("table_member m").
		Joins("left join a2 on m.user_id = a2.id ").
		Joins("left join a3 on m.user_id = a3.user_id ").
		Unscoped().
		Where(condition, params...)
	err = GetDB().Raw("select "+strings.Join(alias, ",")+" from ? a ", subQuery.SubQuery()).Scan(results).Error
	return
}

func main() {

	var (
		err     error
		filter  FilterDo
		results Summary
	)
	fields := map[string]string{
		"today_num":          "num1",
		"yes_num":            "num2",
		"last_num":           "num3",
		"today_num+last_num": "num4", // 组合
	}
	err = SumFields(&filter, results, fields)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("results = ", results)
}

适用于使用汇总统计表的时候

 类似资料: