List Column Type in GORM?

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

List Column Type in GORM?

问题

type Competition struct {
	ID           uint64 `gorm:"primaryKey;autoIncrement"`
	UserID       uint64
	Title        string  `gorm:"size:100;not null" validate:"required,min=10,max=100"`
	Description  string  `gorm:"size:5000;not null" validate:"required,min=100,max=5000"`
	Latitude     float64 `gorm:"not null" validate:"required"`
	Longitude    float64 `gorm:"not null" validate:"required"`
	Address      string  `gorm:"size:1000;not null" validate:"required,max=1000"`
	StartingDate string  `gorm:"not null" validate:"required,min=10,max=10"`
	StartingTime string  `gorm:"not null" validate:"required,min=5,max=5"`
	EndingTime   string
	Images       []string `gorm:"type:text[]"`
	CreatedAt    uint64   `gorm:"autoCreateTime"`
	UpdatedAt    uint64   `gorm:"autoUpdateTime:milli"`

	// relationships
	Users []*User `gorm:"many2many:participant;"`
}

我正在使用PostgreSQL,并且需要添加一个列表数据类型的列,但是[]string在将模型迁移到数据库时不起作用,并且会生成异常。我已经将Images字段的类型更改为text[],这样就可以在PostgreSQL中创建一个数组类型的列了。

英文:
type Competition struct {
	ID           uint64 `gorm:"primaryKey;autoIncrement"`
	UserID       uint64
	Title        string  `gorm:"size:100;not null" validate:"required,min=10,max=100"`
	Description  string  `gorm:"size:5000;not null" validate:"required,min=100,max=5000"`
	Latitude     float64 `gorm:"not null" validate:"required"`
	Longitude    float64 `gorm:"not null" validate:"required"`
	Address      string  `gorm:"size:1000;not null" validate:"required,max=1000"`
	StartingDate string  `gorm:"not null" validate:"required,min=10,max=10"`
	StartingTime string  `gorm:"not null" validate:"required,min=5,max=5"`
	EndingTime   string
	Images       []string
	CreatedAt    uint64 `gorm:"autoCreateTime"`
	UpdatedAt    uint64 `gorm:"autoUpdateTime:milli"`

	// relationships
	Users []*User `gorm:"many2many:participant;"`
}

I am using postgresql and need to add list data type column but []string is not working and generating exception while migrating models to db.

答案1

得分: 1

根据metalisticpain在帖子链接中提到的,你需要在PostgreSQL中使用pq.StringArray类型才能使其工作。

只需将Images字段更改如下:

Images    pq.StringArray `gorm:"type:text[]"`

不要忘记导入包含pq.StringArray实现的github.com/lib/pq库。

并确保在插入数据时使用pq.Array进行包装。

英文:

As metalisticpain stated through a post link that you need to use pq.StringArray type postgres for it to work

Just change Images Field as below

Images    pq.StringArray `gorm:"type:text[]"`

Don't forget to import github.com/lib/pq library which contains pq.StringArray implementation

And make sure while inserting data you wrap it with pq.Array

huangapple
  • 本文由 发表于 2022年9月21日 04:27:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/73792287.html
匿名

发表评论

匿名网友

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

确定