go - 使用 GORM 从 Postgresql 检索表名称

标签 go go-gorm

希望从我的 postgresql 数据库中检索表名。现在,我知道在 Go 中您可以使用 sql 和 pq 驱动程序,但我使用 GORM 在 REST API 中执行查询。

PostgreSQL中的table_name类型是“information_schema.sql_identifier”。这就是我试图做的,但类型不是字符串。

var tables []string
if err := db.Table("information_schema.tables").Select("table_name").Where("table_schema = ?", "public").Find(&tables).Error; err != nil {
    panic(err)
}

最佳答案

TL;DR

要使用 Gorm 将单个列值选择到 slice 中,您可以使用 db.Pluck 帮助程序:

var tables []string
if err := db.Table("information_schema.tables").Where("table_schema = ?", "public").Pluck("table_name", &tables).Error; err != nil {
    panic(err)
}

TS;WM

考虑到这一点,SELECT 语句返回一组具有一个或多个列的行。为了将它们映射到 Go 代码,我们需要一种结构体,以便 Gorm 可以理解哪一列映射到该结构体的哪个字段。即使您只选择 1 个单列,它也只是一个具有 1 个单字段的结构。

type Table struct {
    TableName   string
    // more fields if needed...
}

所以你的输出变量应该是[]*Table:

var tables []*Table
if err := db.Table("information_schema.tables").Select("table_name").Where("table_schema = ?", "public").Find(&tables).Error; err != nil {
    panic(err)
}

注意:如果您不想修改 slice 内的元素,也可以是 []Table

如果您不想定义结构,可以使用db.Pluck函数,它只是此类代码的帮助器:

rows, err := db.Table("information_schema.tables").Select("table_name").Where("table_schema = ?", "public").Rows()
defer rows.Close()

var tables []string
var name string
for rows.Next() {
    row.Scan(&name)
    tables = append(tables, name)
}

关于go - 使用 GORM 从 Postgresql 检索表名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60976342/

相关文章:

go - 在 Go 中映射 DTO 时减少重复代码的数量

mongodb - Golang/mgo : How can I store Date (not ISODate) in mongodb?

concurrency - 使用共享 map 的不错的惯用方式

GORM Golang 如何优化这段代码

go - 使用CloudSQL和Google App Engine在Gorm上部署Go后端时出现服务器错误500

sql - 如何使用 GORM 从多对多关系相关的其他表中过滤包含实体的表?

go - 在 Go 中是否有实现静态变量的模式?

go - gorm 预加载不适用于对象集合吗?

go - 获取对象返回空字符串作为值Golang

rest - 如何将 UINT(不是 uint64 或 uint32)与字符串进行比较