Dewinpena
Dewinpena

Reputation: 91

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

Upvotes: 0

Views: 577

Answers (2)

M_x
M_x

Reputation: 867

  • You can also do it in this way
db.Preload("User").Select("ID", "Username").Find(&posts)

Upvotes: 1

Emin Laletovic
Emin Laletovic

Reputation: 4324

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)

Upvotes: 1

Related Questions