GORM协会

GORM协会,go,go-gorm,Go,Go Gorm,给定已在数据库中创建的以下数据结构,并且相应表中的行中存在有效数据:- type Deployment struct { gorm.Model Name string `gorm:"unique_index:idx_name"` RestAPIUser string RestAPIPass string Servers []Server model *Model } type Server struct {

给定已在数据库中创建的以下数据结构,并且相应表中的行中存在有效数据:-

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
}
我正在尝试选择所有部署,并让GORM为每个部署自动填充服务器

不幸的是,它不能做到这一点。我尝试了几种使用Associations()func的方法,但似乎无法使其发挥作用。我似乎必须手动执行此操作:-

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
}
有人对我如何让GORM自动填写服务器字段有什么建议吗?谢谢

试试看

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