Golang - GORM 如何为现有表创建模型?

2024-03-26

根据此链接的来源:https://gorm.io/docs/index.html 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

当且仅当我们通过声明struct与现有表同名。为了简单起见,我可以更改代码中的名称吗?


只需实施Tabler https://pkg.go.dev/gorm.io/gorm@v1.20.12/schema#Tabler接口如指定在文档中 https://gorm.io/docs/conventions.html#TableName。像这样:

func (User) TableName() string {
  return "a_table_name"
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Golang - GORM 如何为现有表创建模型? 的相关文章

随机推荐