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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog