1

我正在使用go-pghttps://github.com/go-pg/pg)和这段代码:

type Book struct {
  id   int
  name string
}

var books []Book
err := db.Model(&books).Select()

一切正常,但我需要添加一个像这样的“虚拟”列:

concat ('info:', 'id:', id, '...') AS info

我尝试使用:

query.ColumnExpr("concat ('info:', 'id:', id, '...') AS info")

但:

  1. go-pg 抱怨:error="pg: can't find column=info in model=Book (try discard_unknown_columns)"

  2. go-pg 不再包含列id并且name在查询中:concat...仅!

我可以理解,因为现在 go-pg 不知道如何绑定数据,但我真的需要只能从数据库中检索的字符串。

有办法吗?

我可以使用下面这样的自定义类型吗?

type CustomBook struct {
  Info string
  Book
}

这有意义吗?

4

1 回答 1

2

这种方法可以为你工作:

type Book struct {
  ID   int
  Name string
  Info string `pg:"-"`
}

...
db.Model(&books).ColumnExpr("book.*").ColumnExpr("CONCAT('id:', id, 'name:', name) AS info").Select()

pg:"-"忽略结构字段并且它没有被创建也不会产生任何错误

这个被忽略的列记录在这里:https ://pg.uptrace.dev/models/

另一种方法,根据您的要求,可能是这样的:

var r []struct {
  Name string
  Info string
}

db.Model((*Book)(nil)).Column("name").ColumnExpr("CONCAT('id:', id, 'name:', name) AS info").Select(&r)

第二个记录在这里:https ://pg.uptrace.dev/queries/

于 2020-12-31T11:52:30.653 回答