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

报告相同问题?