Gorm: 更改默认生成列的名称

创建于 2017-05-18  ·  3评论  ·  资料来源: go-gorm/gorm

嗨,是否可以覆盖列的名称:ID、created_at、updated_at、deleted_at?

据我所知,我可以使用以下函数设置表的名称:

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

有可能但有列吗? 这是因为项目的数据模型已经建立了字段的名称,例如我们没有_updated_at_而是_ModificationTimestamp_,我该怎么做?

最有用的评论

只是不要在您的结构中嵌入默认模式。 如果你看看它是如何定义的,你会看到:

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

您可以在自己的模型中定义这些字段,也可以使用不同的名称创建自己的基本模型并将其嵌入。

所有3条评论

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嗨,谢谢。 但我正试图让 gorm 为自动创建的列取其他名称:created_at、updated_at、id。 我尝试了你所说的但它给出了错误,因为例如已指定列 created_at :
column "created_at" specified more than once)

只是不要在您的结构中嵌入默认模式。 如果你看看它是如何定义的,你会看到:

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

您可以在自己的模型中定义这些字段,也可以使用不同的名称创建自己的基本模型并将其嵌入。

此页面是否有帮助?
0 / 5 - 0 等级

相关问题

pjebs picture pjebs  ·  3评论

fieryorc picture fieryorc  ·  3评论

Quentin-M picture Quentin-M  ·  3评论

Ganitzsh picture Ganitzsh  ·  3评论

izouxv picture izouxv  ·  3评论