package main
import (
"log"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
// User Model struct
type User struct {
ID string
Name string
}
func main() {
postgresDSN := "host=localhost port=5432 user=test dbname=test_db password=passwd sslmode=disable"
db, err := gorm.Open(postgres.Open(postgresDSN), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
db.Debug()
db.AutoMigrate(&User{})
err = db.Migrator().AddColumn(&User{}, "age")
if err != nil {
log.Fatal(err)
}
}
Hey Guys, When I executed the program, I got the following error:
$ go run main.go
2020/10/11 22:26:37 failed to look up field with name: age
exit status 1
How can I dynamically add new fields to an old table? Thx :)
hello @JmilkFan
db.Migrator().AddColumn() is a ORM method, gorm execute method after confirming the field in struct.
maybe you can add column use sql instead of ORM method:
db.Exec("ALTER TABLE user ADD name varchar(64);")
good luck!
Most helpful comment
hello @JmilkFan
db.Migrator().AddColumn()is a ORM method, gorm execute method after confirming the field in struct.maybe you can add column use sql instead of ORM method:
db.Exec("ALTER TABLE user ADD name varchar(64);")
good luck!