我想加载帖子,并且是作者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": "1112@gmail.com", "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 关注
- 77 浏览
添加回答
举报
0/150
提交
取消