You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GORM模型中定义bigint数组的数组类型

在GORM中定义PostgreSQL二维整数数组列

针对你遇到的{{1,2},{2,3}}这种二维整数数组格式(对应PostgreSQL的integer[][]类型),直接使用pq.Array(pq.Int64Array)无效是因为pq.Int64Array仅支持一维数组,需要自定义类型来适配二维场景,具体步骤如下:

1. 自定义二维数组类型并实现数据库接口

导入pq库后,定义二维整数数组类型,并实现sql.Scanner和driver.Valuer接口,让GORM能正确解析和写入数据库:

import (
    "database/sql/driver"
    "github.com/lib/pq"
)

// Int64Matrix 定义二维整数数组类型
type Int64Matrix [][]int64

// Scan 实现sql.Scanner接口,从数据库读取数据
func (m *Int64Matrix) Scan(value interface{}) error {
    return pq.Array(m).Scan(value)
}

// Value 实现driver.Valuer接口,向数据库写入数据
func (m Int64Matrix) Value() (driver.Value, error) {
    return pq.Array(m).Value()
}

2. 在GORM模型中使用自定义类型

在模型结构体中,将目标字段类型指定为Int64Matrix,同时通过gorm:"type:integer[][]"明确数据库列类型:

type YourModel struct {
    ID         uint           `gorm:"primaryKey"`
    MatrixData Int64Matrix    `gorm:"type:integer[][]"`
    // 其他字段...
}

3. 使用示例

创建和查询数据时,直接操作二维数组即可:

// 创建记录
db.Create(&YourModel{
    MatrixData: Int64Matrix{{1,2}, {2,3}},
})

// 查询记录
var model YourModel
db.First(&model, 1)
// model.MatrixData 会被解析为 [][]int64{{1,2}, {2,3}}

这样就能完美适配数据库中返回的{{1,2},{2,3}}格式二维数组了。

内容的提问来源于stack exchange,提问作者Stuart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 23:42:27