Gorm: How to use Migrator AddColumn method?

Created on 11 Oct 2020  ·  1Comment  ·  Source: go-gorm/gorm

Question

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 :)

question

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!

>All comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Ganitzsh picture Ganitzsh  ·  3Comments

hypertornado picture hypertornado  ·  3Comments

izouxv picture izouxv  ·  3Comments

satb picture satb  ·  3Comments

youtwo123 picture youtwo123  ·  3Comments