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 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行