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

Adding an array of integers as a data type in a Gorm Model

我正在尝试使用 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 的回答更新。我尝试了建议的代码,但出现了类似的错误。

“恐慌:无效 sql 为 postgres 键入 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")
}

您需要使用底层库中的自定义类型:

type Game struct {                                           
        gorm.Model                                           
        GameCode    string                                      
        GameName    string                                      
        DeckType    pq.Int64Array `gorm:"type:integer[]"`
        GameEndDate string    
}   

// example insertion
dt := []int64{1, 2, 3}   
                                                                                
db.Create(&Game{GameCode: "xxx", GameName: "xxx", DeckType: pq.Int64Array(dt), GameEndDate: "xxx"})