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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题