英文:
Gorm - upgrading columns constraint with migration
问题
如何使用gorm进行迁移?例如,我需要向列添加约束。我更改了我的模型(下面是一个简化的示例),但是根据文档,AutoMigrate方法不会更改列的约束。
那么如何实现呢?我在文档中找不到有用的信息。
起始模型:
type User struct {
gorm.Model
Name string
}
我想要将其更新为:
type User struct {
gorm.Model
Name string `gorm:"not null"`
}
英文:
How do you perform a Migration with gorm? For example, I need to add a constraint to a column. I changed my model (simplified example below), but the AutoMigrate method, according to the docs, will not change column's constraints.
How do you achieve it then? I cannot find anything useful in the docs
Starting model:
type User struct {
gorm.Model
Name string
}
I would like to update it like this:
type User struct {
gorm.Model
Name string `gorm:"not null"`
}
答案1
得分: 2
当添加一个not null
约束时,如果现有记录不符合新的条件,则还需要添加一个default
值。定义可以是这样的:
type User struct {
gorm.Model
Name string `gorm:"not null;default:'fillertext'"`
}
正如@putu所说,ALTER TABLE
肯定可以工作,但是您仍然需要最初添加一个默认值,以确保不符合要求的行满足新的要求。一旦完成了这个步骤,如果您希望,可以删除默认值,然后迁移将按预期工作。
英文:
When adding a not null
constraint, then a default
value will also need to be added for when the existing records do not meet the new criteria. The definition could be something like:
type User struct {
gorm.Model
Name string `gorm:"not null;default:'fillertext'"`
}
As @putu said, ALTER TABLE
will certainly work, but you would still need to add a default value initially to ensure the non-comforming rows meet the new requirements. Once this has been done you can remove the default value if you desire and the migration will work as intended from that point on.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论