【问题标题】:How to insert column in already existing table如何在现有表中插入列
【发布时间】:2021-04-12 07:20:15
【问题描述】:

我正在创建具有有限数据的表 Account,即具有 id 、 name 和 reference。 如果我得到 MembersIntersection 数组,那么根据它们的大小,我想在已创建的表中添加这些额外的列

type Account struct {
    ID         string `json:"Id,omitempty" validate:"max=36"`
    Name       string `json:"name,omitempty" validate:"required,max=255"`
    Reference  string `json:"reference,omitempty" validate:"required,max=64"`
    MembersIntersection []DimensionMemberIntersection `json:"dimensionMemberIntersection,omitempty" 
}

如何使用 gorm 做到这一点?

【问题讨论】:

  • 您好,您可以编辑您的问题以解释“我正在创建表帐户”的含义吗?你想在你的数据库中添加一个 SQL 表吗?还是您想像“包含查询结果的数组”那样构建一个表?

标签: go go-gorm


【解决方案1】:

可以使用 Gorm 迁移器界面。 我不建议这样做,基于用户输入的表格结构听起来不是一个好主意。也许您可以将此变量输入存储在 JSON 列中?

这是一个使用 gorm 迁移器界面的示例。完整的文档是here

您将需要版本 2 的 gorm。

type DimensionMemberIntersection string

type Account struct {
    ID         string 
    Name       string 
    Reference  string 
    MembersIntersection []DimensionMemberIntersection
    // This assumes the underlying type of DimensionMemberIntersection is string
}

account := Account{}

for _, col := range account.MembersIntersection {
    if !db.Migrator().HasColumn(&Account{}, col) {
        db.Migrator().AddColumn(&Account{}, col)
    }
}

【讨论】:

  • 感谢您的回复。我需要更新我的 go 版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多