我想加載帖子,并且是作者ID和電子郵件,而無需加載任何其他內容。它不需要急于加載,我只需要獲取所有帖子,只包括作者ID和用戶名我的當前查詢posts := []interfaces.Post{}db.Model("User").Find(&posts)type Post struct{ gorm.Model Title string Body string UserID uint User User}type User struct{ gorm.Model Username string Email string Password string}當前響應 { "ID": 1, "CreatedAt": "2021-01-09T19:11:42.063274-05:00", "UpdatedAt": "2021-01-09T19:11:42.063274-05:00", "DeletedAt": null, "Title": "What does the fox say", "Body": "whawhhwjg", "UserID": 1, "User": { "ID": 1, "CreatedAt": "2021-01-09T19:01:28.70267-05:00", "UpdatedAt": "2021-01-09T19:01:28.70267-05:00", "DeletedAt": null, "Username": "12345", "Email": "[email protected]", "Password": "$2a$04$T1841Dc52MwjSJ2PaPnTwuFASai6zkGw8WFcuQbO1fi9Nug7R3Iqq" } },我正在尋找的響應 { "ID": 1, "CreatedAt": "2021-01-09T19:11:42.063274-05:00", "UpdatedAt": "2021-01-09T19:11:42.063274-05:00", "DeletedAt": null, "Title": "What does the fox say", "Body": "whawhhwjg", "UserID": 1, "User": { "ID": 1, "Username": "12345", } },
2 回答

白衣非少年
TA貢獻1155條經驗 獲得超0個贊
您可以使用該方法選擇特定字段。Select
dm.Model("User").Select("ID", "Email", "Username").Find(&posts)
或者,您可以使用這樣的方法。Preload
db.Preload("User", func (db *gorm.DB) *gorm.DB {
return db.Select("ID", "Email", "Username")
}).
Find(&posts)
- 2 回答
- 0 關注
- 93 瀏覽
添加回答
舉報
0/150
提交
取消