我是否需要使用 gorm (golang) 在我的数据库中读取和写入两个不同的对象?

Do I need to have two different objects to read and to write in my database using gorm (golang)?

gorm 在文档中告诉 "Base model definition gorm.Model, including fields ID, CreatedAt, UpdatedAt, DeletedAt, you could embed it in your model, or only write those fields you want":

// Base Model's definition
type Model struct {
  ID        uint `gorm:"primary_key"`
  CreatedAt time.Time
  UpdatedAt time.Time
  DeletedAt *time.Time
}

// Add fields `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`
type User struct {
  gorm.Model
  Name string
}

// Only need field `ID`, `CreatedAt`
type User struct {
  ID        uint
  CreatedAt time.Time
  Name      string
}

根据文档,我希望用户只有一个定义,所以我创建了一个这样的对象:

type User struct {
  gorm.Model
  ID        uint
  CreatedAt time.Time
  Name      string
}

但是如果我执行 DB.CreateTable(&User{}),我会从 postgres 得到以下错误:

(pq: column "id" specified more than once)
(pq: column "created_at" specified more than once)

所以我必须有两个不同的对象:

type CreateUser struct {
  gorm.Model
  Name string
}

type RetrieveUser struct {
  gorm.Model
  ID        uint
  CreatedAt time.Time
  Name      string
}

所以我可以做一个DB.CreateTable(&CreateUser{})

它非常难看,我一定是漏掉了什么,有什么想法吗?

好的,请阅读 gorm.Model 背后的代码,我得到了答案。

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

这意味着我刚刚学习了继承在 go 中的工作原理!