英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论