猿问

gorm :单独的数据库存储模型和查询发送模型

发送 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 中。但对我来说,这似乎是解决这个问题的丰富方法,因此我想知道是否存在更好的解决方案?


更高效的解决方案


手掌心
浏览 93回答 1
1回答

繁花不似锦

不完全确定您的问题,但无论如何让我尝试提供帮助。通常我会执行以下操作,但我相信有更好的方法可以做到。对于模型,我将在如下所示的 pkg 中准备它们。// For reading data from form.type CreatePostForm struct {&nbsp; &nbsp; Title string `json:"title"`&nbsp; &nbsp; Body&nbsp; string `json:"body"`}// For interactions with database.type Post struct {&nbsp; &nbsp; gorm.Model&nbsp; &nbsp; Title string&nbsp;&nbsp; &nbsp; Body&nbsp; string}type Posts []Post// For data transfer object (sending over to UI etc).type PostDto struct {&nbsp; &nbsp; Title&nbsp; &nbsp; &nbsp; &nbsp;string&nbsp;&nbsp; &nbsp; Body&nbsp; &nbsp; &nbsp; &nbsp; string&nbsp; &nbsp; CreatedDate time.Time&nbsp; &nbsp; CreatedBy&nbsp; &nbsp;string}type PostsDto []PostDto// Convert form data into database model for database operations.func (p PostCreateForm) ToCreateModel() (*Post, error) {&nbsp; &nbsp; // 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) {&nbsp; &nbsp; // 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 {&nbsp; &nbsp; dtos := make(PostsDto, len(ps))&nbsp; &nbsp; for key, post := range ps {&nbsp; &nbsp; &nbsp; &nbsp; dtos[key] = post.ToDto()&nbsp; &nbsp; }&nbsp; &nbsp; return dtos}所以基本上从上面你从数据库中获取数据后,你基本上可以通过使用类似的方法将 Posts 类型转换为 PostsDto 类型Posts.ToDto()。数据库适配器将在另一个 pkg 中,它基本上完成读取/写入数据库的工作,我不会分享,因为你的问题更多是发送另一组数据用于 CRUD 操作。同样,我希望这对您有所帮助,但我仍然认为可能有更好的方法来做到这一点。
随时随地看视频慕课网APP

相关分类

Go
我要回答