Gorm: can you change the gorm.Model definition?

Created on 27 Sep 2019  ·  1Comment  ·  Source: go-gorm/gorm

gorm.Model

now:

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

new:

type Model struct {
    ID        uint       `gorm:"primary_key" json:"id"`
    CreatedAt time.Time  `json:"created_at"`
    UpdatedAt time.Time  `json:"updated_at"`
    DeletedAt *time.Time `json:"deleted_at"`
}

Most helpful comment

You don't have to use gorm.Model in your structs. gorm.Model isn't required and doesn't do anything apart from providing these fields. Instead, GORM looks for fields with the names "ID", "CreatedAt", and so on and updates them accordingly (relevant documentation).

This means that you can define your own "base model" struct:

type MyModel struct {
  ID        uint       `gorm:"primary_key" json:"id"`
  CreatedAt time.Time  `json:"created_at"`
  UpdatedAt time.Time  `json:"updated_at"`
  DeletedAt *time.Time `json:"deleted_at"`
}

and use it in your structs:

type User struct {
  MyModel

  Name string `json:"name"`
}

The fields from MyModel will be treated the same way as those defined in gorm.Model.

>All comments

You don't have to use gorm.Model in your structs. gorm.Model isn't required and doesn't do anything apart from providing these fields. Instead, GORM looks for fields with the names "ID", "CreatedAt", and so on and updates them accordingly (relevant documentation).

This means that you can define your own "base model" struct:

type MyModel struct {
  ID        uint       `gorm:"primary_key" json:"id"`
  CreatedAt time.Time  `json:"created_at"`
  UpdatedAt time.Time  `json:"updated_at"`
  DeletedAt *time.Time `json:"deleted_at"`
}

and use it in your structs:

type User struct {
  MyModel

  Name string `json:"name"`
}

The fields from MyModel will be treated the same way as those defined in gorm.Model.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

izouxv picture izouxv  ·  3Comments

leebrooks0 picture leebrooks0  ·  3Comments

youtwo123 picture youtwo123  ·  3Comments

easonlin404 picture easonlin404  ·  3Comments

rfyiamcool picture rfyiamcool  ·  3Comments