如何指定数组gorm golang的默认值?
Posted
技术标签:
【中文标题】如何指定数组gorm golang的默认值?【英文标题】:how to specify default value of array gorm golang? 【发布时间】:2022-01-11 22:44:30 【问题描述】:我用的是gorm和postgresql,这是模型
type Board struct
Id uint `gorm:"primaryKey;autoIncrement;unique" json:"id"`
Owner uint `json:"owner"`
Name string `json:"name"`
Contributors []int `gorm:"type:jsonb" json:"contributors"`
GeneratedLink string `gorm:"default:''" json:"generated_link"`
Todos []TodoStructure `gorm:"type:jsonb;default:[]" json:"todos"`
type TodoStructure struct
Id string
Text string
Completed bool
Important bool
在 Todo 值中,我将默认值指定为 [] 但是当我运行应用程序时出现此错误
ERROR: syntax error at or near "[" (SQLSTATE 42601)
[100.528ms] [rows:0] CREATE TABLE "boards" ("id" bigserial UNIQUE,"owner" bigint,"name" text,"contributors" jsonb,"generated_link" text DEFAULT '',"todos" jsonb DEFAULT [],PRIMARY KEY ("id"))
panic: ERROR: syntax error at or near "[" (SQLSTATE 42601)
那么如何指定数组为默认值呢?
【问题讨论】:
【参考方案1】:尝试像这样引用gorm:"type:jsonb;default:'[]'" json:"todos"
type Board struct
Id uint `gorm:"primaryKey;autoIncrement;unique" json:"id"`
Owner uint `json:"owner"`
Name string `json:"name"`
Contributors []int `gorm:"type:jsonb" json:"contributors"`
GeneratedLink string `gorm:"default:''" json:"generated_link"`
Todos []TodoStructure `gorm:"type:jsonb;default:'[]'" json:"todos"`
更多参考你可以参考这个link
【讨论】:
现在尝试创建板时出现错误:sql: Scan error on column index 1, name "todos": unsupported Scan, storing driver.Value type []uint8 into type *[]models.TodoStructure
以上是关于如何指定数组gorm golang的默认值?的主要内容,如果未能解决你的问题,请参考以下文章