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{})
這是非常醜陋的,我必須失去了一些東西,什麼想法?
Go中沒有繼承。你會想看看[Struct嵌入](https://golang.org/doc/effective_go.html#embedding) – JimB
謝謝你這個重要的精度! – Adrien