GORM嵌入的结构体无法迁移到SQL。

huangapple go评论88阅读模式
英文:

GORM embedded struct not getting migrated to SQL

问题

我在GORM中声明了以下模型:

type DBModel struct {
	ID        uint       `gorm:"primaryKey"`
	CreatedAt *time.Time `json:"_"`
	UpdatedAt *time.Time `json:"_"`
	DeletedAt *time.Time `json:"_"`
	ClientID  uint       `gorm:"not_null"`
}

type Address struct {
	address string
	city    string
	state   string
	pincode int
	country string
}

type Office struct {
	DBModel        DBModel `gorm:"embedded"`
	Address        Address `gorm:"embedded"`
	Name           string
}

在运行以下代码时:

func Init(db *gorm.DB) {
    DB = db
	DB.AutoMigrate(&models.Office{})
}

被迁移的Office表具有以下字段:

id
created_at
updated_at
deleted_at
client_id
name

为什么Address结构体没有被嵌入?

英文:

I am declaring the following models in GORM :

type DBModel struct {
	ID        uint       `gorm:"primaryKey"`
	CreatedAt *time.Time `json:"_"`
	UpdatedAt *time.Time `json:"_"`
	DeletedAt *time.Time `json:"_"`
	ClientID  uint       `gorm:"not_null"`
}

type Address struct {
	address string
	city    string
	state   string
	pincode int
	country string
}

type Office struct {
	DBModel        DBModel `gorm:"embedded"`
	Address        Address `gorm:"embedded"`
	Name           string
}

On running

func Init(db *gorm.DB) {
    DB = db
	DB.AutoMigrate(&models.Office{})
}

The Office table being migrated has fields:

id
created_at
updated_at
deleted_at
client_id
name

Why is the Address struct not being embedded ?

答案1

得分: 0

好的,我明白了。

Address 结构体的字段应该是导出字段
字段必须以大写字母开头才能被导出。

修改 Address 结构体如下:

type Address struct {
    Address string
    City    string
    State   string
    Pincode int
    Country string
}
英文:

Okay understood it.

The fields of the Address struct should be exported fields.
Fields must start with capital letters to be exported.

Changing the Address struct does the work :

type Address struct {
    Address string
    City    string
    State   string
    Pincode int
    Country string
}

huangapple
  • 本文由 发表于 2021年9月4日 18:09:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/69054329.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定