發送 gorm 模型的有效方法是什么,該模型與用于將資料存盤在資料庫中的 gorm 模型不同?
該Post模型(結構)用于將資料存盤在資料庫中。
type Post struct {
gorm.Model
Title string
Body string
}
但我想使用這個PostReadgorm 模型,而不是發送回用戶。因為以后可能會有額外的變數添加到這個資料庫中,這些變數不會存盤在這個資料庫中。(或者額外的變數可能來自其他服務或資料庫)
type PostRead struct {
ID string `json:"id" gorm:"primary_key"`
Title string `json:"title"`
Body string `json:"body"`
CreatedAt time.Time `json:"createAt"`
UpdatedAt time.Time `json:"updatedAt"`
...
<other variables to be added later>
}
這是我當前的控制器代碼,用于發回資料:
func PostGetAll(c *gin.Context) {
posts, err := services.PostGetAllService()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err})
return
}
c.JSON(http.StatusOK, gin.H{"posts": posts})
}
這是我的服務代碼,用于從資料庫中獲取資料:
func PostGetAllService() ([]models.Post, error) {
var posts []models.Post
result := initializers.DB.Find(&posts)
if result.Error != nil {
return nil, errors.New(result.Error.Error())
}
return posts, nil
}
注意:我知道我可以PostRead在控制器函式中創建一個 SliceArray PostGetAll(),然后用于append()將來自帖子 ( Post) 的資料添加到 SliceArray 中。但對我來說,這似乎是解決這個問題的豐富方法,因此我想知道是否存在更好的解決方案?
更高效的解決方案
uj5u.com熱心網友回復:
不完全確定您的問題,但無論如何讓我嘗試提供幫助。
通常我會執行以下操作,但我相信有更好的方法可以做到。
對于模型,我將在如下所示的 pkg 中準備它們。
// 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
}
所以基本上從上面你從資料庫中獲取資料后,你基本上可以通過使用類似的方法將 Posts 型別轉換為 PostsDto 型別Posts.ToDto()。
資料庫配接器將在另一個 pkg 中,它基本上完成讀取/寫入資料庫的作業,我不會分享,因為你的問題更多是發送另一組資料用于 CRUD 操作。
同樣,我希望這對您有所幫助,但我仍然認為可能有更好的方法來做到這一點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/535752.html
標籤:去go-gorm
