鍍金池/ 問答/GO  網(wǎng)絡(luò)安全  HTML/ go gorm select 了字段后 結(jié)果集還是所有的struct都被返回,

go gorm select 了字段后 結(jié)果集還是所有的struct都被返回,只是其他字段為空

go gorm select 了字段后 結(jié)果集還是所有的struct都被返回,只是其他字段為空

問題出現(xiàn)的環(huán)境背景及自己嘗試過哪些方法

相關(guān)代碼

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 設(shè)置對(duì)應(yīng)的外鍵
CreditCard *CreditCard `gorm:"foreignkey:CardID"`
CardID uint

}

實(shí)際結(jié)果

[
{
"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
}
]

期望結(jié)果

[{
"id":6,
"username":"hello",
"phone":"18672858779"
},
{
"id":9,
"username":"hello",
"phone":"18672858779"
}
]
回答
編輯回答
命于你

因?yàn)槟闶褂檬堑模?/p>

Find(&user)

其中,&user 是一個(gè) stuct ,肯定是一個(gè)完整的結(jié)構(gòu),沒有值的字段會(huì)有默認(rèn)值

如果不想顯示那些的話,可以使用 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)

文檔,見這里

2017年12月3日 03:54