Matjam
Matjam

Reputation: 134

GORM Associations

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? Thanks!

Upvotes: 1

Views: 644

Answers (1)

RuNpiXelruN
RuNpiXelruN

Reputation: 1920

Try

m.db.Preload("Servers").Find(&Deployment{})

Upvotes: 1

Related Questions