gpt4 book ai didi

go - DropColumn 如果存在于 GORM 中

转载 作者:数据小太阳 更新时间:2023-10-29 03:31:49 24 4
gpt4 key购买 nike

引用this 帮助文档,如果存在语法 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 如果它是 has no error 。否则,它会 return the error

我希望这能回答您的问题。 :)

关于go - DropColumn 如果存在于 GORM 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44563162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com