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

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:"-"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 微信小程序跑脚本授权的问题
  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏
  • ¥15 STM32串口接收问题
  • ¥15 腾讯IOA系统怎么在文件夹里修改办公网络的连接
  • ¥15 filenotfounderror:文件是存在的,权限也给了,但还一直报错
  • ¥15 MATLAB和mosek的求解问题
  • ¥20 修改中兴光猫sn的时候提示失败
  • ¥15 java大作业爬取网页
  • ¥15 怎么获取欧易的btc永续合约和交割合约的5m级的历史数据用来回测套利策略?
  • ¥15 有没有办法利用libusb读取usb设备数据