anonymous-dev
anonymous-dev

Reputation: 3499

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

I have a model struct

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),
    )
}

I want the customer to have Contact data so I have a contact struct. But whenever I try to run the server

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),
    )
}

I get

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

But I don't want it to be on it's own seperate table. So how do I prevent that? I tried using

`gorm:"-"`

But if I then read the record as json all the values are empty

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

So my question is why do I need the scanner and valuer or a foreign key if I don't want it to be on it's own seperate table?

Upvotes: 0

Views: 1252

Answers (1)

anonymous-dev
anonymous-dev

Reputation: 3499

I had to use gorm:"embedded" instead of gorm:"-" as described in the docs

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

Upvotes: 1

Related Questions