2019-08-26 14:55
浏览 941

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?

图片转代码服务由CSDN问答提供 功能建议

我有一个many2many关联(用于返回JSON)。 在模型中声明:

  // models / school.go 
 ID int`gorm:“ primary_key”`
名称字符串`gorm:  “ not not null”`
认证[] Armreditation`gorm:“ many2many:school_accreditation;” 

效果很好。 我在json中返回了关联。 问题是我在 school_accreditation 表中还有一个附加字段,但响应中未包含

我有 试图为该关联声明一个模型,如此答案中所建议的:

 < 代码> // models / schoolAccreditation.go 
 StartedAt time.Time`gorm:“ not null”`

但目前为止还无法正常工作。 是否需要声明一些其他配置? 还是要修改?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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:"-"`
    解决 无用
    打赏 举报

相关推荐 更多相似问题