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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效