0

go gorm select 了字段后 结果集还是所有的struct都被返回,只是其他字段为空

问题出现的环境背景及自己尝试过哪些方法

相关代码

db.Debug().Where(s).Select([]string{"id","username","phone"}).Find(&user)

type User struct {

gorm.Model
Username string `json:"username"`
Phone string `json:"phone"`
Type int8 `json:"type"`
Order []Order `gorm:"ForeignKey:UId"`   // hasMany 设置对应的外键
CreditCard *CreditCard `gorm:"foreignkey:CardID"`
CardID uint

}

实际结果

[
{
"id": 3,
"created_at": "0001-01-01T00:00:00Z",
"updated_at": "0001-01-01T00:00:00Z",
"deleted_at": null,
"username": "hello",
"phone": "18672858778",
"type": 0,
"Order": null,
"CreditCard": null,
"CardID": 0
},
{
"id": 6,
"created_at": "0001-01-01T00:00:00Z",
"updated_at": "0001-01-01T00:00:00Z",
"deleted_at": null,
"username": "hello",
"phone": "18672858778",
"type": 0,
"Order": null,
"CreditCard": null,
"CardID": 0
},
{
"id": 9,
"created_at": "0001-01-01T00:00:00Z",
"updated_at": "0001-01-01T00:00:00Z",
"deleted_at": null,
"username": "hello",
"phone": "18672858779",
"type": 0,
"Order": null,
"CreditCard": null,
"CardID": 0
},
{
"id": 12,
"created_at": "0001-01-01T00:00:00Z",
"updated_at": "0001-01-01T00:00:00Z",
"deleted_at": null,
"username": "hello",
"phone": "18672858779",
"type": 0,
"Order": null,
"CreditCard": null,
"CardID": 0
}
]

期望结果

[{
"id":6,
"username":"hello",
"phone":"18672858779"
},
{
"id":9,
"username":"hello",
"phone":"18672858779"
}
]
tcc 60
2018-07-27 提问
2 个回答
0

已采纳

因为你使用是的:

Find(&user)

其中,&user 是一个 stuct ,肯定是一个完整的结构,没有值的字段会有默认值

如果不想显示那些的话,可以使用 Scan

type Result struct {
  Name string
  Age  int
}

var result Result
db.Table("users").Select("name, age").Where("name = ?", 3).Scan(&result)

// Raw SQL
db.Raw("SELECT name, age FROM users WHERE name = ?", 3).Scan(&result)

文档,见这里

0

你好,我现在遇到了一个问题是你的升级版:
以下是我的数据库中一个表的 struct 信息,是服务告警信息

type Alarm struct {

gorm.Model
EventId    string
AlarmTime  time.Time
Priority   int
Status     string
TplId      int
StraId     int
ExpId      int
Metric     string
Tags       string
LeftValue  string
RightValue string
Endpoint   string
Step       int
Note       string `gorm:"size: 500"`
Pdl        string
Domain     string
Path       string
Cluster    string

}

我对数据库的一个字段进行了Group by操作
func (topTime TopfiveTime) GetIncidentsfive(mark string) []Alarm{

var topFiveList []Alarm
topStartTime, _ := parseWithLocation("Asia/Shanghai", topTime.StartTime)
topEndTime, _ :=  parseWithLocation("Asia/Shanghai", topTime.EndTime)

db.Select(mark + ",count(*) AS mark_cnt").
    Where("status = 'problem' AND created_at BETWEEN ? AND ?",topStartTime, topEndTime).
    Group(mark).
    Order("mark_cnt DESC").
    Limit(6).
    Scan(&topFiveList)
fmt.Println(topFiveList)

return topFiveList

}

在mysql中执行生成如下结果:
图片描述

生成的结果与Alarm struct 不一致了,导致返回的信息是原Alarm struct的值(当然是一些不可用的错误中),
求大佬解释如何能正确返回,如数据库展示的正确数据吗?

撰写答案

推广链接