在 Gorm 模型中添加整数数组作为数据类型

我正在尝试使用 Gorm 在单个 postgresql 字段中保存一组数字。


该数组需要是一个包含 2 到 13 个数字的列表:[1, 2, 3, 5, 8, 13, 21, 40, 1000]


保存单个 int64 时一切正常。当我尝试更改模型以考虑 int64 数组时,它给了我以下错误:


“恐慌:postgres 的 sql 类型(切片)无效”


我的 Gorm 模型是:


type Game struct {

    gorm.Model

    GameCode    string

    GameName    string

    DeckType    []int64

    GameEndDate string

}

根据@pacuna 的回答进行更新。我尝试了建议的代码,我得到了类似的错误。


“恐慌:postgres 的无效 sql 类型 Int64Array(切片)”


这是完整的代码块:


package main


import (

    "fmt"


    "github.com/jinzhu/gorm"

    _ "github.com/jinzhu/gorm/dialects/postgres"

    pq "github.com/lib/pq"

)


var db *gorm.DB


// Test -- Model for Game table

type Test struct {

    gorm.Model                                           

    GameCode    string                                      

    GameName    string                                      

    DeckType    pq.Int64Array    

    GameEndDate string   

}



func main() {

    db, err := gorm.Open("postgres", "host=localhost port=5432 user=fullstack dbname=scratch_game sslmode=disable")

    if err != nil {

        fmt.Println(err.Error())

        panic("Failed to connect to database...")

    }

    defer db.Close()



    dt := []int64{1, 2, 3}



    db.AutoMigrate(&Test{})

    fmt.Println("Table Created")


    db.Create(&Test{GameCode: "xxx", GameName: "xxx", DeckType: pq.Int64Array(dt), GameEndDate: "xxx"})

    fmt.Println("Record Added")

}


人到中年有点甜
浏览 354回答 1
1回答

慕桂英4014372

您需要使用底层库中的自定义类型:type Game struct {                                                   gorm.Model                                                   GameCode    string                                              GameName    string                                              DeckType    pq.Int64Array `gorm:"type:integer[]"`        GameEndDate string    }   // example insertiondt := []int64{1, 2, 3}                                                                                   db.Create(&Game{GameCode: "xxx", GameName: "xxx", DeckType: pq.Int64Array(dt), GameEndDate: "xxx"})    
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go