Gorm: Change name of default generated columns

Created on 18 May 2017  ·  3Comments  ·  Source: go-gorm/gorm

Hi, is possible to override the name the columns: ID, created_at, updated_at, deleted_at ?

As far as I know I can set for example the name of the table with the function:

func (StructType) TableName() string {
    return "MyCustomName"
}

Is it possible but with the columns? this is because the data-model of the project already have stablished the namesof the fields, and for example we don't have _updated_at_ but _ModificationTimestamp_ so, how can I do it?

Most helpful comment

Just don't embed default moded in your struct. If you look how it's defined you will see:

type Model struct {
    ID        uint `gorm:"primary_key"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time `sql:"index"`
}

You can define this fields in your own model or create you own base model with different names and embed it.

All 3 comments

http://jinzhu.me/gorm/models.html#conventions

// Overriding Column Name
type Animal struct {
    AnimalId    int64     `gorm:"column:beast_id"`         // set column name to `beast_id`
    Birthday    time.Time `gorm:"column:day_of_the_beast"` // set column name to `day_of_the_beast`
    Age         int64     `gorm:"column:age_of_the_beast"` // set column name to `age_of_the_beast`
}

@smacker Hi, thank you. But I exactly am trying to make gorm to take other name for the columns that are autocreated: created_at, updated_at, id. I tried what you said but it gave error because for example the column created_at is already especified:
column "created_at" specified more than once)

Just don't embed default moded in your struct. If you look how it's defined you will see:

type Model struct {
    ID        uint `gorm:"primary_key"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time `sql:"index"`
}

You can define this fields in your own model or create you own base model with different names and embed it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zeropool picture zeropool  ·  3Comments

bramp picture bramp  ·  3Comments

koalacxr picture koalacxr  ·  3Comments

kumarsiva07 picture kumarsiva07  ·  3Comments

alanyuen picture alanyuen  ·  3Comments