登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-15 09:03:33 192浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《添加整数数组作为 Gorm 模型中的数据类型》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我正在尝试使用 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")
}

解决方案


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

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

以上就是《添加整数数组作为 Gorm 模型中的数据类型》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>