登录
首页 >  Golang >  Go问答

在现有的表格中添加新的列

来源:stackoverflow

时间:2024-02-28 14:51:24 223浏览 收藏

大家好,我们又见面了啊~本文《在现有的表格中添加新的列》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

我正在使用有限的数据创建表帐户,即 id 、名称和参考。 如果我得到 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 做到这一点?


正确答案


可以使用 gorm 迁移器界面。 但我不建议这样做,基于用户输入的表结构听起来不是一个好主意。也许您可以将此变量输入存储在 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)
    }
}

本篇关于《在现有的表格中添加新的列》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>