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 評価

関連する問題

zeropool picture zeropool  ·  3コメント

corvinusy picture corvinusy  ·  3コメント

Quentin-M picture Quentin-M  ·  3コメント

hypertornado picture hypertornado  ·  3コメント

koalacxr picture koalacxr  ·  3コメント