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"
}
]
因为你使用是的:
其中,&user 是一个 stuct ,肯定是一个完整的结构,没有值的字段会有默认值
如果不想显示那些的话,可以使用 Scan
文档,见这里