duannuo7878
2019-04-29 08:52
浏览 161

使用数组字段将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条回答 默认 最新

相关推荐 更多相似问题