gorm icon indicating copy to clipboard operation
gorm copied to clipboard

How do I get Preload with Select to work?

Open cinjon opened this issue 1 year ago • 4 comments

Your Question

My two types are below. I would like to return the user plus its known last latitude and longitude and nothing else. However, I am struggling to do this and the best I have right now is the following that returns everything in the embedded location.

database.DB.Debug().Preload("Locations").Where("user_id = ?", uid).Find(&users)

How do I get this to work properly? All attempts to select from the location object are just producing null, e.g.

database.DB.Debug().Preload("Locations").Where("user_id = ?", uid).Select('user.id, locations.latitude').Find(&users)

type Location struct {
	gorm.Model
	UserID string    `json:"userId"`
	User   User  `gorm:"foreignKey:userID;references:Id"`
	Latitude   float64   `json:"latitude"`
	Longitude  float64   `json:"longitude"`
	RecordedAt time.Time `json:"recordedAt,omitempty"`
}

type User struct {
	gorm.Model
	Id       string    `gorm:"type:uuid;primaryKey" json:"id"`
	Name     string    `json:"name"`
	Email    string    `json:"email;unique"`
	Locations               []Location `json:"locations"`
}

The document you expected this should be explained

Expected answer

I expected that I'd get back select arguments from locations and users.

cinjon avatar May 15 '23 16:05 cinjon