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

alanyuen picture alanyuen  路  3Comments

corvinusy picture corvinusy  路  3Comments

superwf picture superwf  路  3Comments

zeropool picture zeropool  路  3Comments

satb picture satb  路  3Comments