1 回答
TA贡献1851条经验 获得超4个赞
不完全确定您的问题,但无论如何让我尝试提供帮助。
通常我会执行以下操作,但我相信有更好的方法可以做到。
对于模型,我将在如下所示的 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 操作。
同样,我希望这对您有所帮助,但我仍然认为可能有更好的方法来做到这一点。
- 1 回答
- 0 关注
- 92 浏览
添加回答
举报