Given the following data structure which has been created in the database and there is valid data in the rows in the appropriate tables:-
type Deployment struct {
gorm.Model
Name string `gorm:"unique_index:idx_name"`
RestAPIUser string
RestAPIPass string
Servers []Server
model *Model
}
type Server struct {
gorm.Model
DeploymentID uint
Hostname string `gorm:"unique_index:idx_hostname"`
RestPort string
Version string
}
I'm trying to select all Deployments and have GORM automatically fill the Servers for each Deployment.
Unfortunately, it doesn't do this. I've tried several variations of using the Associations() func but I can't seem to get it to work. I seem to have to do this manually:-
func (m *Model) GetDeployments() ([]Deployment, error) {
deployments := []Deployment{}
err := m.db.Find(&deployments).Error
if err != nil {
return nil, err
}
deploymentsWithServers := []Deployment{}
for _, d := range deployments {
servers := []Server{}
err := m.db.Model(&d).Association("Servers").Find(&servers).Error
if err != nil {
return nil, err
}
d.Servers = servers
deploymentsWithServers = append(deploymentsWithServers, d)
}
return deploymentsWithServers, nil
}
Does anyone have any suggestions how I can get GORM to fill the Servers field automatically? The documentation is trying to help but doesn't really explain how this is supposed to work with a complete example. Thanks!
You can simplify this on a one liner if you want by doing:
func (m *Model) GetDeployments() ([]Deployment, error) {
deployments := []Deployment{}
return deployments, m.db.Preload("Servers").Find(&deployments).Error
}
I think the term you're looking for is "auto preload". I'm also looking for this feature, but I'm not sure if it lacks documentation or has never been implemented.
http://gorm.io/crud.html#auto-preload
@jinzhu the link you provided doesn't appear to mention auto-preload.
It seems that the documentation was redesigned. Here's the new link: http://gorm.io/docs/preload.html#Auto-Preloading.
Most helpful comment
http://gorm.io/crud.html#auto-preload