登录
首页 >  Golang >  Go问答

在Golang的Gorm中如何设定数组的默认值?

来源:stackoverflow

时间:2024-02-22 10:30:26 453浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《在Golang的Gorm中如何设定数组的默认值?》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

问题内容

我使用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)

那么如何指定数组作为默认值呢?


正确答案


尝试像这样添加引号 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

今天关于《在Golang的Gorm中如何设定数组的默认值?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>