登录
首页 >  Golang >  Go问答

gorm Many2many 和关联表中的附加字段

来源:stackoverflow

时间:2024-04-28 16:15:33 319浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《gorm Many2many 和关联表中的附加字段》,聊聊,我们一起来看看吧!

问题内容

我有一个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 表中有一个附加字段,但它包含在响应中。

我尝试声明一个关联模型,如本答案中提出的:

// models/schoolAccreditation.go
package models

import "time"

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

但目前还不起作用。是否需要声明一些额外的配置?或者修改?


解决方案


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

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

理论要掌握,实操不能落!以上关于《gorm Many2many 和关联表中的附加字段》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>