duannuo7878 2019-04-29 08:52
浏览 167
已采纳

使用数组字段将postgres行转换为golang结构

I am having postgres db table as

CREATE TABLE foo (
name varchar(50),
types varchar(50)[],
role varchar[10]
);

and corresponding struct in go:

type Foo struct {
Name string `db:"name"`
Types []string `db:"types"`
Role string `db:"role"`
}

I want to fetch db rows into my struct. Right now I am able to do this by using:

var foo Foo
query := `SELECT name, types, roles FROM foo LIMIT 1`
err = dbConn.QueryRow(query).Scan(&foo.Name,  pq.Array(&foo.Types), &foo.Role)

But I want to achieve the same using direct mapping. Something like:

var foo []Foo
query := `SELECT name, types, roles FROM foo`
dbWrapper.err = dbConn.Select(&foo, query)

Above snippet gives me error because of Types being pq array. Is it possible to directly map pq array as a part of struct?

  • 写回答

2条回答 默认 最新

  • dougang8233 2019-05-08 07:35
    关注

    Thanks to https://stackoverflow.com/a/44385791/10138004, I am able to solve this pq driver for sqlx (https://godoc.org/github.com/lib/pq) itself by replacing []string with pq.StringArray.

    So, updated struct looks like:

    type Foo struct {
    Name string `db:"name"`
    Types pq.StringArray `db:"types"` //this is what changed.
    Role string `db:"role"`
    }
    

    and direct mapping is working like a charm now

    var foo []Foo
    query := `SELECT name, types, roles FROM foo`
    dbWrapper.err = dbConn.Select(&foo, query)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 数电设计题 没有设计思路 不知道用什么芯片进行设计 求提供设计思路
  • ¥15 在动态多目标优化问题中,第一幅图展示的是问题DF6的相关定义和绘制的POS和POF图,请问图中公式PS(t)和PF(t)是如何推导的
  • ¥60 设计一种优化算法结合案例给出智能仓储四向穿梭车的调度计划
  • ¥15 Errno2:No such file or directory,在当前文件确实没有该图片,怎么解决?
  • ¥15 博世摄像头数据存储的问题(iscsi)
  • ¥15 如何实现对学生籍贯信息管理系统的选择排序
  • ¥15 写一个51单片机的时钟代码
  • ¥15 git clone报错
  • ¥15 3d-slicer超声造影动态图像导入报错
  • ¥15 化工过程分析与合成问题求解决