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

如何将gorm.Record转为数组或直接获取PostgreSQL数组数据?

解决Gorm扫描PostgreSQL数组到int64切片的问题

直接将[]int64传入Scan会导致Gorm把它当作接收多行结果的容器,而非单个字段的数组值,所以才会出现类型异常。以下是几种可行的解决方式:

方法1:用结构体包装目标字段

定义包含数组字段的结构体,将查询结果扫描进结构体实例后取出数组:

type GiveawayParticipants struct {
    Participants []int64
}

var result GiveawayParticipants
db.Table("giveaways").Select("Participants").Where("Name = ?", name).Scan(&result)
winner_selection := result.Participants
// 此时winner_selection为正常[]int64,可执行追加、迭代等操作

方法2:借助PostgreSQL专属类型转换

使用Gorm PostgreSQL驱动提供的pgtype.Array类型接收数据,再转换为普通[]int64:

import "gorm.io/driver/postgres"

var pgArray pgtype.Int64Array
db.Table("giveaways").Select("Participants").Where("Name = ?", name).Scan(&pgArray)

// 转换为普通int64切片
winner_selection := make([]int64, len(pgArray.Elements))
for i, elem := range pgArray.Elements {
    if elem.Valid {
        winner_selection[i] = elem.Int64
    }
}

方法3:直接使用Raw查询扫描

通过Raw方法执行原生查询,直接将结果扫描进切片:

var winner_selection []int64
db.Raw("SELECT Participants FROM giveaways WHERE Name = ?", name).Scan(&winner_selection)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:56:10