Golang:gorm 使用 Find(&model) 进行非 gorm 迁移 table

Golang: gorm use Find(&model) for non gorm migrate table

有table customer_account (postgres) 是从YII2迁移过来的

DDL:

CREATE TABLE public.test_table (
  id INTEGER PRIMARY KEY NOT NULL DEFAULT nextval('test_table_id_seq'::regclass),
  data JSONB
);

在 go 项目中,我尝试从这个 table 中获取价值。

type TableGo struct {
    Id int
    Data string `gorm:"type:jsonb"`
}

    table := TableGo{}
    db.Where("id = ?", 75).Find(&table)
    println(table.Data)

但是有(pq: relation "table_gos" does not exist)

如果没有 db.AutoMigrate(&TableGo{}),我如何 link 构造 table?

找到解决方案:

func(TableGo) TableName() string {
    return "account_status"
}

我认为您的迁移脚本中的 table 名称有误。因为它不在 GORM 约定中。如果您想使用该名称,可以在您的模型中使用以下方法自定义 table 名称。

func (m *Model) TableName() string {
    return "custom_table_name"
}