V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
ifconfig
V2EX  ›  Go 编程语言

问老哥们一个 go gorm 的问题

  •  
  •   ifconfig · 2020-06-12 23:48:13 +08:00 · 1843 次点击
    这是一个创建于 1425 天前的主题,其中的信息可能已经有所发展或是发生改变。
    type Countries struct {
    	ID    uint32 `json:"id"`
    	Name  string `json:"name"`
    	Image string `json:"image" sql:"-"`
    }
    
    type CountriesAll struct {
    	Countries
    	IsComment uint8 `json:"is_common"`
    }
    

    举个例子,A 接口可能需要 Countries 的数据,B 接口可能需要 CountriesAll 的数据,C 接口需要 CountriesSimple 的数据,这样岂不是要定义蛮多个结构体的?

    现在的烦恼是,用户表有十几个字段,可能一些接口只需要精简的字段,一些接口需要完整的字段,给后台的接口又是另外一些字段,所以为了保持接口的精简和一些不必要的字段输出,在一个 model 内定义多个结构体,这样合理么?还是大家是怎么做的?

    PS:不过据我所知哈,身边的写 go 的朋友是用 sql 原生写法,不存在这个问题,只不过我比较喜欢模型的写法写起来比较精简也好维护

    8 条回复    2020-06-13 15:30:26 +08:00
    lvsshuttao
        1
    lvsshuttao  
       2020-06-13 00:15:34 +08:00
    我平时都是这样写的
    ```
    type Country struct { // 用于数据库的结构体,没有多余的字段
    Id int64 `json:"id"`
    CreatedAt time.Time `json:"created_at"`
    UpdatedAt time.Time `json:"updated_at"`
    Name string `json:"name"`
    Image string `json:"image"`
    }

    type ParamCountry struct { // 用于创建记录的结构体
    Id int64 `json:"id"`
    Name string `json:"name"`
    Image string `json:"image"`
    }

    func (p *ParamCountry) ToModel() model.Country {
    return model.Country{
    Id: p.Id,
    // ...
    }
    }

    type RespCountry struct { // 用于返回数据的结构体
    Id int64 `json:"id"`
    Name string `json:"name"`
    Image string `json:"image"`
    }

    func (p *RespCountry) FromModel(m *model.Country) {
    p.Id = m.Id
    // ...
    }

    type RespCountryDetail struct { // 扩展了 RespCountry
    RespCountry
    // 更多的字段
    }
    ```

    分开写有利于扩展;比如查询结果需要其它表字段,就可以直接往 `RespCountry` 中添加其它表的字段;如果查询参数需要支持按关键字 `keyword`(不属于任何表) 查询,也可以直接往 `ParamCountry` 添加
    airplayxcom
        2
    airplayxcom  
       2020-06-13 09:27:22 +08:00 via iPhone
    ifconfig
        3
    ifconfig  
    OP
       2020-06-13 09:29:18 +08:00
    zjj19950716
        4
    zjj19950716  
       2020-06-13 09:33:47 +08:00 via iPhone
    zjj19950716
        5
    zjj19950716  
       2020-06-13 09:35:18 +08:00 via iPhone
    ifconfig
        6
    ifconfig  
    OP
       2020-06-13 10:06:10 +08:00
    @zjj19950716 学习到了,感谢分享
    yrj
        7
    yrj  
       2020-06-13 12:55:58 +08:00 via iPad
    好巧,正好这几天也在用 gorm,也遇到了楼主同样的问题。持续关注。
    Hanggi
        8
    Hanggi  
       2020-06-13 15:30:26 +08:00
    一个 model 应该对应一个表,如果你有多种数据格式返回的需求,应该创建多个不同的 struct 专门用于返回。
    可以借鉴 #5 楼给的链接里得各种方法,把不同的返回结构进行拆分、合并、嵌套。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1164 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 22:54 · PVG 06:54 · LAX 15:54 · JFK 18:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.