DropColumn 如果存在于 GORM 中

DropColumn if exists in GORM

参考 this 帮助文档,有一个 drop table if exists 语法 db.DropTableIfExists(&User{}, "products") 但对于 db.Model(&User{}).DropColumn("description") DropColumnIfExists 不存在。我应该用什么来实现 DropColumn(如果该列存在,否则不存在。)

What should I use to implement DropColumn (if the column exists, otherwise not.)

回答你的问题...

继续吧。您可以使用 db.Model(&User{}).DropColumn("description")

优雅地处理错误。 记住,在 Golang 中,Errors are values

func main() {
    db.AutoMigrate(&User{})

    err := db.Model(&User{}).DropColumn("description").Error
    if err != nil {
        // Do whatever you want to do!
        log.Print("ERROR: We expect the description column to be 
drop-able")
    }
}

在后台,gorm 会 execute raw postgresql query if it has no error. Otherwise, it will return the error

我希望这会回答你的问题。 :)

截至 2021 年 Mohsin 的回答更新:

What should I use to implement DropColumn (if the column exists, otherwise not.)

当前版本(3.5.5)不再支持2017syntax/api

来自GORM Migration Reference

err = db.Migrator().DropColumn(&AuthUser{}, "name")
if err != nil {
    // Do whatever you want to do!
    log.Print("ERROR: We expect the description column to be drop-able")
}