2016-12-09 24 views
1

GORM文檔中告訴「基礎模型定義gorm.Model,包括域ID,CreatedAt,UpdatedAt,DeletedAt,你可以將它嵌入到你的模型,或只寫你想要的那些字段」:我是否需要使用gorm(golang)來讀取和寫入數據庫中的兩個不同的對象?

// 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{})

這是非常醜陋的,我必須失去了一些東西,什麼想法?

回答

1

好吧,只需閱讀gorm.Model背後的代碼,我就得到了答案。

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

這意味着我只是傾向於如何繼承工作在去!

+1

Go中沒有繼承。你會想看看[Struct嵌入](https://golang.org/doc/effective_go.html#embedding) – JimB

+0

謝謝你這個重要的精度! – Adrien

相關問題