jonin
jonin

Reputation: 232

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

I am trying to save an array of numbers in a single postgresql field using Gorm.

The array needs to be a list with between 2 & 13 numbers: [1, 2, 3, 5, 8, 13, 21, 40, 1000]

Everything was working when saving a single int64. When I tried changing the model to account for an array of int64's it gives me the following error:

"panic: invalid sql type (slice) for postgres"

my Gorm model is:

type Game struct {
    gorm.Model
    GameCode    string
    GameName    string
    DeckType    []int64
    GameEndDate string
}

Update based on answer from @pacuna. I tried the suggested code and I get a similar error.

"panic: invalid sql type Int64Array (slice) for postgres"

Here is the full code block:

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

Upvotes: 17

Views: 28180

Answers (1)

pacuna
pacuna

Reputation: 2099

You need to use custom types from the underlying library:

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

Upvotes: 33

Related Questions