douke8473 2016-12-09 21:45
浏览 218
已采纳

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

gorm tell in the documentation that "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
}

Following the documentation, I expect to have only one definition of User, so I create an object like that:

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

But if I do a DB.CreateTable(&User{}), I get the following errors from postgres:

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

So I have to have two different objects :

type CreateUser struct {
  gorm.Model
  Name string
}

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

So I can do a DB.CreateTable(&CreateUser{})

It is very ugly and I must be missing something, any idea?

  • 写回答

1条回答 默认 最新

  • donglu5041 2016-12-09 21:56
    关注

    Ok, just read the code behind gorm.Model and I got my answer.

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

    It means I just leaned how inheritance works in go !

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备