不废话,直接上代码
type Pool struct {
*gorm.DB
}
func NewPool(db *gorm.DB) *Pool {
return &Pool{DB: db}
}
func DataToMap[K int64 | string, V int64 | string | float64 | float32](pool *Pool, table Model, NewMap map[K]V, key string, value string, args ...interface{}) error {
tx := pool.Model(table).Select(key, value)
if len(args) == 1 {
tx.Where(args[0])
} else if len(args) >= 2 {
tx.Where(args[0], args[1:])
}
rows, err := tx.Rows()
if err != nil {
return err
}
defer rows.Close()
var k K
var v V
for rows.Next() {
err := rows.Scan(&k, &v)
if err != nil {
return err
}
NewMap[k] = v
}
return nil
}
调用示例
username := make(map[int64]string)
DataToMap(pool, &model.User{}, username, "id", "username")
DataToMap(pool, &model.User{}, username, "id", "username", "`id`<?", 5)
得到结果:
{
"1": "老男孩",
"2": "LEO",
"3": "Lucifer",
"4": "Tom"
}