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")
}
db. Model is the ordinary way of doing things. It allows you to tell gorm which model struct this operation relates to. It isn't always needed, as for example a simple Find with the right struct type will infer the model automatically.
GORM provides official support for sqlite , mysql , postgres , sqlserver . Some databases may be compatible with the mysql or postgres dialect, in which case you could just use the dialect for those databases. For others, you can create a new driver, it needs to implement the dialect interface.
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"})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With