1 回答
TA贡献1775条经验 获得超8个赞
TableName()通过为我的每个模型实现该方法,我能够实现我想要的:
type MyObject struct {
ID uint `grom:"column:id" json:"id"`
OwnerID uint `gorm:"column:owner_id" json:"owner_id"`
Owner Owner `json:"owner"`
...
}
func (MyObject) TableName() {
return "my_schema.my_object"
}
type Owner struct {
ID uint `gorm:"column:id" json:"id"`
...
}
func (Owner) TableName() {
return "my_schema.owner"
}
然后,我可以在如下查询中使用它:
myObject := &models.MyObject{}
result := ls.Model(myObject).
Where("id = ?", id). //assume any valid value for id
First(myObject).
Related(&myObject.Owner)
return myObject, processResult(result)
最后,当向我的服务器发出请求时,MyObject我得到了Owner数据库中相关对象的所有数据:
$ curl "http://localhost:8080/api/objetcs/related/1" | jq // passing 1 as object id value in url params
{
"id": "1", // taken from UrlParam
"name": "testobj",
"owner": {
"id": "1", // using foreign key owner_id
"name": "testowner",
"config": configJson // json object taken from row in my_schema.owner table in the DB
}
}
}
- 1 回答
- 0 关注
- 117 浏览
添加回答
举报