1 回答

TA貢獻1851條經(jīng)驗 獲得超4個贊
不完全確定您的問題,但無論如何讓我嘗試提供幫助。
通常我會執(zhí)行以下操作,但我相信有更好的方法可以做到。
對于模型,我將在如下所示的 pkg 中準(zhǔn)備它們。
// For reading data from form.
type CreatePostForm struct {
Title string `json:"title"`
Body string `json:"body"`
}
// For interactions with database.
type Post struct {
gorm.Model
Title string
Body string
}
type Posts []Post
// For data transfer object (sending over to UI etc).
type PostDto struct {
Title string
Body string
CreatedDate time.Time
CreatedBy string
}
type PostsDto []PostDto
// Convert form data into database model for database operations.
func (p PostCreateForm) ToCreateModel() (*Post, error) {
// Process logic here which is basically creating a new Post model and returning it..
}
// Convert database model into DTO to reply to request etc.
func (p Post) ToDto() (*PostDto, error) {
// Process logic here which is basically creating a new PostDto model and returning it..
}
// Convert many Posts to many DTOs.
func (ps Posts) ToDto() PostsDto {
dtos := make(PostsDto, len(ps))
for key, post := range ps {
dtos[key] = post.ToDto()
}
return dtos
}
所以基本上從上面你從數(shù)據(jù)庫中獲取數(shù)據(jù)后,你基本上可以通過使用類似的方法將 Posts 類型轉(zhuǎn)換為 PostsDto 類型Posts.ToDto()。
數(shù)據(jù)庫適配器將在另一個 pkg 中,它基本上完成讀取/寫入數(shù)據(jù)庫的工作,我不會分享,因為你的問題更多是發(fā)送另一組數(shù)據(jù)用于 CRUD 操作。
同樣,我希望這對您有所幫助,但我仍然認為可能有更好的方法來做到這一點。
- 1 回答
- 0 關(guān)注
- 111 瀏覽
添加回答
舉報