Golang - GORM 如何为现有 table 创建模型?
Golang - GORM how to create a model for an existing table?
根据此 link 的来源:https://gorm.io/docs/index.html
要声明一个模型,我们这样做:
type User struct {
ID uint
Name string
Email *string
Age uint8
Birthday *time.Time
MemberNumber sql.NullString
ActivatedAt sql.NullTime
CreatedAt time.Time
UpdatedAt time.Time
}
然后 运行 migration
在数据库上创建它。
但是,我找不到任何提及声明数据库中已存在模型的文档。我想是这样的:
type User struct {
ID uint
Name string
This_struct(User).belongs_to_an_existing_table_named("a_table_name") -- this is an example to explaning what I mean
当且仅当我们通过声明一个与现有 table 同名的 struct
来做到这一点。为了简单起见,我可以在我的代码中更改名称吗?
只需实施 Tabler
interface as specified in the docs。像这样:
func (User) TableName() string {
return "a_table_name"
}
根据此 link 的来源:https://gorm.io/docs/index.html
要声明一个模型,我们这样做:
type User struct {
ID uint
Name string
Email *string
Age uint8
Birthday *time.Time
MemberNumber sql.NullString
ActivatedAt sql.NullTime
CreatedAt time.Time
UpdatedAt time.Time
}
然后 运行 migration
在数据库上创建它。
但是,我找不到任何提及声明数据库中已存在模型的文档。我想是这样的:
type User struct {
ID uint
Name string
This_struct(User).belongs_to_an_existing_table_named("a_table_name") -- this is an example to explaning what I mean
当且仅当我们通过声明一个与现有 table 同名的 struct
来做到这一点。为了简单起见,我可以在我的代码中更改名称吗?
只需实施 Tabler
interface as specified in the docs。像这样:
func (User) TableName() string {
return "a_table_name"
}