Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

go - Load model with with association

I would like to load the post and is author id and email without loading anything else.

It doesn't need to be eager loading I just need to get all posts and include only the authors id and username

My current query

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
}

Current response

        {
            "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"
            }
        },

Response I'm looking for

 {
            "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",
            }
        },
question from:https://stackoverflow.com/questions/65650366/load-model-with-with-association

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the Select method to select the specific fields.

dm.Model("User").Select("ID", "Email", "Username").Find(&posts)

Or, you can use the Preload method like this.

db.Preload("User", func (db *gorm.DB) *gorm.DB {
  return db.Select("ID", "Email", "Username")
}).
Find(&posts)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...