【问题标题】:gorm many2many and additional fields in association table关联表中的 gorm many2many 和附加字段
【发布时间】:2019-12-30 18:56:18
【问题描述】:

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

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

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

我已尝试为 this answer 中提议的关联声明一个模型:

// models/schoolAccreditation.go
package models

import "time"

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

但到目前为止它还不起作用。是否有一些额外的配置要声明?还是要修改?

【问题讨论】:

  • “问题是我在school_accreditation 表中有一个附加字段,但它包含在响应中。”错字?或者你是说你想exclude json 中的一个字段?如果是这样,您可以使用json:"-" 字段标签来实现。
  • 对不起,我修改了“不包括在内”。我希望附加字段出现在 json 响应中。感谢您指出错字。 :)

标签: postgresql go model go-gorm


【解决方案1】:

回答我自己,我将链接模型中的字段添加为“忽略”并且它有效,该列会自动从关联表中检索。

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:"-"`
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-20
    • 2017-06-22
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 2023-03-04
    • 2015-05-26
    • 1970-01-01
    相关资源
    最近更新 更多