如何在现有 table 中插入列
How to insert column in already existing table
我正在创建 table 数据有限的帐户,即 id 、 name 和 reference 。
如果我得到 MembersIntersection 数组,然后根据它们的大小,我想在已经创建的 table
中添加那些额外的列
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 执行此操作?
您可以使用 Gorm 迁移器界面。 不过我不建议这样做,基于用户输入的 table 结构听起来不是个好主意。也许您可以将此变量输入存储在 JSON 列中?
这里是一个使用 gorm 迁移器界面的例子。完整的文档是 here
您将需要 gorm 的第 2 版。
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)
}
}
我正在创建 table 数据有限的帐户,即 id 、 name 和 reference 。 如果我得到 MembersIntersection 数组,然后根据它们的大小,我想在已经创建的 table
中添加那些额外的列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 执行此操作?
您可以使用 Gorm 迁移器界面。 不过我不建议这样做,基于用户输入的 table 结构听起来不是个好主意。也许您可以将此变量输入存储在 JSON 列中?
这里是一个使用 gorm 迁移器界面的例子。完整的文档是 here
您将需要 gorm 的第 2 版。
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)
}
}