duanli0687 2017-10-06 17:58
浏览 32
已采纳

GORM协会

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!

  • 写回答

1条回答 默认 最新

  • doulao1934 2017-10-22 20:36
    关注

    Try

    m.db.Preload("Servers").Find(&Deployment{})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示