我们在带有w / c API的API中添加了一个include参数,客户端可以用来包含关系
// request
GET /api/events?include=team1
[{
"id": <event_id>,
"name": <event_name>,
"team1": {
"id": <team_id>,
"name": <team_name>
}
}]
// code
type Event struct {
ID int64 `gorm:"primary_key" json:"id"`
Team1ID int64 `json:"-"`
Team1 Team `json:"team1"`
}
var event Event
Db.Preload("Team1").Find(&event, 1)
c.JSON(http.StatusOK, event)
但是我们也希望能够做到这一点:
// request
GET /api/events
[{
"id": <event_id>,
"name": <event_name>,
"team1": <team1_id>
}]
现在team1字段只是一个ID。
Go中有一种简单的方法吗?
我想我可以通过使用a来做到这一点map[string]interface{}
,就像在db中提取事件之后,将事件结构转换为a map[string]interface{}
并进行修改。但是我想知道是否有一个更简单的解决方案。
这里是我使用的尝试map[string]interface{}
- https://play.golang.org/p/-19MWtqhE3。该代码非常冗长。这个想法是map[string]interface{}
用于每个结构,然后组成包括相关资源的顶级资源。
有什么更好的方法呢?
实际上,您可以将team1设置为一个接口,然后将其转换为值,显然可以进行正确的验证。
type Event struct {
ID int64 `gorm:"primary_key" json:"id"`
Team1ID int64 `json:"-"`
Team1 interface{} `json:"team1"`
Team1Struct Team `json:"-"`
}
然后评估:
if value, ok := evt.Team1.(Team); ok {
// The passed value is a Team struct
event.Team1Struct = value
} else {
// The passed value is a string (or something else...)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句