我用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脚本中指定了Foreignkey关系
最佳答案
通过为每个模型实现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
}
}
}
关于postgresql - postgres,go-gorm-无法预加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61069888/