Golang: gorm在非gorm迁移表中使用Find(&model)。

huangapple go评论76阅读模式
英文:

Golang: gorm use Find(&model) for non gorm migrate 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项目中,我尝试从这个表中获取值。

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{})的情况下链接表的结构?

英文:

There is table customer_account (postgres) which one was migrate from YII2.

DDL:

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

In go project i try to get value from this table.

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

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

But there is (pq: relation "table_gos" does not exist)

How i can link structure which table without db.AutoMigrate(&TableGo{})?

答案1

得分: 0

找到了解决方案:

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

这段代码的作用是返回表名为"account_status"。

英文:

Found the solution:

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

答案2

得分: 0

我认为你的迁移脚本中的表名是错误的,因为它不符合 GORM 的命名规范。如果你想使用那个名字,你可以在你的模型中使用以下方法来设置自定义的表名。

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

I think table name in your migration script is wrong. Because it is not in GORM convention. If you want to use that name,you can use following method in your model for custom table name.

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

huangapple
  • 本文由 发表于 2016年9月6日 18:36:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/39346924.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定