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

我正在尝试使用 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 脚本中指定了外键关系


慕尼黑的夜晚无繁华
浏览 118回答 1
1回答

www说

TableName()通过为我的每个模型实现该方法,我能够实现我想要的:type MyObject struct {&nbsp; &nbsp; ID&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; uint&nbsp; &nbsp; &nbsp; `grom:"column:id" json:"id"`&nbsp; &nbsp; OwnerID&nbsp; &nbsp; &nbsp; &nbsp;uint&nbsp; &nbsp; &nbsp; `gorm:"column:owner_id" json:"owner_id"`&nbsp; &nbsp; Owner&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Owner&nbsp; &nbsp; &nbsp;`json:"owner"`&nbsp; &nbsp; ...}func (MyObject) TableName() {&nbsp; &nbsp; return "my_schema.my_object"}type Owner struct {&nbsp; &nbsp; ID&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;uint&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; `gorm:"column:id" json:"id"`&nbsp; &nbsp; ...}func (Owner) TableName() {&nbsp; &nbsp; return "my_schema.owner"}然后,我可以在如下查询中使用它:myObject := &models.MyObject{}result := ls.Model(myObject).&nbsp; &nbsp; Where("id = ?", id).&nbsp; //assume any valid value for id&nbsp; &nbsp; First(myObject).&nbsp; &nbsp; Related(&myObject.Owner)return myObject, processResult(result)最后,当向我的服务器发出请求时,MyObject我得到了Owner数据库中相关对象的所有数据:$ curl "http://localhost:8080/api/objetcs/related/1" | jq&nbsp; // passing 1 as object id value in url params{&nbsp; "id": "1", // taken from UrlParam&nbsp; "name": "testobj",&nbsp; "owner": {&nbsp; &nbsp; "id": "1", // using foreign key owner_id&nbsp; &nbsp; "name": "testowner",&nbsp; &nbsp; "config": configJson // json object taken from row in my_schema.owner table in the DB&nbsp; &nbsp; }&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go