【问题标题】:Adding an array of integers as a data type in a Gorm Model在 Gorm 模型中添加整数数组作为数据类型
【发布时间】:2020-08-05 00:12:28
【问题描述】:

我正在尝试使用 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 (slice)”

这是完整的代码块:

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")
}

【问题讨论】:

  • 我刚刚更新了我的答案。我在使用数组时添加了该类型的标签。现在它应该可以工作了。

标签: postgresql go go-gorm


【解决方案1】:

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

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"})    

【讨论】:

    猜你喜欢
    • 2019-02-28
    • 2015-05-13
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    相关资源
    最近更新 更多