如何在没有模型的情况下在 gorm 模型结构中使用结构

How can I use a struct in a gorm model struct without it being a model

我有一个模型结构

type Customer struct {
    gorm.Model
    Person  `gorm:"-" json:"person"`
    Contact `gorm:"-" json:"contact"`
    Address `gorm:"-" json:"address"`
}

func (p Customer) Validate() error {
    return validation.ValidateStruct(&p,
        validation.Field(&p.Person),
        validation.Field(&p.Contact),
        validation.Field(&p.Address),
    )
}

我希望客户有联系数据,所以我有一个联系结构。但是每当我尝试 运行 服务器

type Contact struct {
    Tel  string `json:"tel"`
    Mail string `json:"mail"`
    URL  string `json:"url"`
}

func (c Contact) Validate() error {
    return validation.ValidateStruct(&c,
        validation.Field(&c.Tel, validation.Required, is.Digit),
        validation.Field(&c.Mail, validation.Required, is.Email),
        validation.Field(&c.URL, is.URL),
    )
}

我明白了

model.Customer's field Contact, need to define a foreign key for relations or it need to implement the Valuer/Scanner interface

但我不希望它单独存在 table。那么我该如何防止呢?我尝试使用

`gorm:"-"`

但是如果我然后读取记录 json 所有值都是空的

    "contact": {
        "tel": "",
        "mail": "",
        "url": ""
    },

所以我的问题是,如果我不希望它单独存在,为什么我需要扫描仪和估价器或外键 table?

我不得不使用 gorm:"embedded" 而不是文档中描述的 gorm:"-"

https://gorm.io/docs/models.html#Embedded-Struct