postgres,go-gorm-无法预加载数据

Guga Figueiredo:

我用gorm查询我的PostgreSQL上的行时试图预加载一些数据

我在belongs to关联中定义了以下类型

type MyObject struct {
    ID            uint      `grom:"column:id" json:"id"`
    Name          string    `gorm:"column:name" json:"name"`
    OwnerID       uint      `gorm:"column:owner_id" json:"owner_id"`
    Owner         Owner     `json:"owner"`
    ...
}

type Owner struct {
    ID         uint            `gorm:"column:id" json:"id"`
    Name       string          `gorm:"column:name" json:"name"`
    Config     json.RawMessage `gorm:"column:config" sql:"type:json" json:"config"`
    Components []uint8         `gorm:"column:components;type:integer[]" json:"components"`
}

以及postgres db中的表,其行如下

my_schema.my_object

id  | name      | owner_id  | ...
----|-----------|-----------|-----
0   | testobj   | 0         | ...


my_schema.owner

id  | name      | config    | components
----|-----------|-----------|-----------
0   | testowner | <jsonb>   | {0,1,2,3}

我正在使用gorm运行以下查询:

object := &models.MyObject{}

result := ls.Table("my_schema.my_object").
    Preload("Owner").
    Where("id = ?", "0").
    First(object)    

但结果,object我得到以下结构:

{"id": 0, "name": "testobj", "owner_id":0, "owner": {"id": 0, "name": "", "config": nil, "components": nil}}

在数据库创建sql脚本中未指定任何外键关系的错误或警告

Guga Figueiredo:

通过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
    }
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章