duanjuete9206 2019-08-26 14:55
浏览 1224
已采纳

gorm many2many和关联表中的其他字段

I have a many2many association (it is used to return JSON). It's declared in a model:

// models/school.go
type School struct {
    ID                int      `gorm:"primary_key"`
    Name              string `gorm:"not null"`
    Accreditations    []Accreditation `gorm:"many2many:school_accreditation;"` 
}

It works well. I have the association returned in the json. The problem is that I have an additional field in the school_accreditation table but it isn't included in the response.

I have tried to declare a model for the association like proposed in this answer:

// models/schoolAccreditation.go
package models

import "time"

// many to many
type SchoolAccreditation struct {
    StartedAt time.Time `gorm:"not null"`
}

But it doesn't work so far. Is there some additional configuration to declare? Or to modify?

  • 写回答

1条回答 默认 最新

  • duanlang1196 2019-08-27 14:50
    关注

    Answering to myself, I added the field in the linked model as "ignore" and it works, the column is automatically retrieved from the association table.

    type Accreditation struct {
        // "accreditation" table
        ID          int `gorm:"primary_key"`
        Name        string
        Description string
        // "school_accreditation table", so the field is set as ignore with "-"
        EndAt       time.Time `gorm:"-"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Stata链式中介效应代码修改
  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 添加组件无法加载页面,某块加载卡住
  • ¥15 网络科学导论,网络控制
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错