DropColumn if exists in GORM

huangapple go评论83阅读模式
英文:

DropColumn if exists in GORM

问题

根据这个帮助文档,有一个如果存在则删除表的语法db.DropTableIfExists(&User{}, "products"),但是对于db.Model(&User{}).DropColumn("description"),不存在DropColumnIfExists。如果要实现删除列(如果列存在,则删除;否则不删除),应该使用什么方法?

英文:

Refering this help doc, there is a drop table if exists syntax db.DropTableIfExists(&User{}, "products") but for db.Model(&User{}).DropColumn("description") DropColumnIfExists doesn't exists. What should I use to implement DropColumn (if the column exists, otherwise not.)

答案1

得分: 6

你可以使用以下代码来实现DropColumn(如果列存在的话):

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

    err := db.Model(&User{}).DropColumn("description").Error
    if err != nil {
        // 处理错误
        log.Print("错误:我们期望可以删除description列")
    }
}

在底层,gorm会执行原始的PostgreSQL查询(如果没有错误的话)。否则,它会返回错误。

英文:

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

To answer your question...

Go ahead with that. You can use db.Model(&User{}).DropColumn("description").

Just handle the errors gracefully. Remember, in 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")
    }
}

Under the Hood, gorm will execute raw postgresql query if it has no error. Otherwise, it will return the error.

答案2

得分: 1

根据Mohsin的回答更新至2021年:

> 如果存在该列,则应使用什么来实现DropColumn(否则不执行)。

当前版本(3.5.5)不再支持2017年的语法/接口。

GORM迁移参考文档中:

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")
}
英文:

Update to Mohsin's answer as of 2021:

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

the current version (3.5.5) does no more support the syntax/api of 2017

From 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")
}

huangapple
  • 本文由 发表于 2017年6月15日 16:58:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/44563162.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定