如何使用预加载+在带有gorm的预加载对象中选择特定字段

时间:2018-06-29 10:23:51

标签: database go go-gorm

我想知道是否可以使用gorm仅预加载嵌套数据库对象的选定字段。现在,我正在尝试这样做:

DB.Preload("Children", func(db *gorm.DB) *gorm.DB {
    return DB.Select("id")
}).First(&labelset, id)

没有成功。结果是:

{
    "ID": 1,
    "CreatedAt": "2018-06-29T11:32:21.293892+02:00",
    "UpdatedAt": "2018-06-29T11:32:21.293892+02:00",
    "DeletedAt": null,
    "description": "Root test",
    "parent_id": 0,
    "children": []
}

如果将“ id”替换为“ *”,则会得到:

{
    "ID": 1,
    "CreatedAt": "2018-06-29T11:32:21.293892+02:00",
    "UpdatedAt": "2018-06-29T11:32:21.293892+02:00",
    "DeletedAt": null,
    "description": "Root test",
    "parent_id": 0,
    "children": [
        {
           "ID": 2,
           "CreatedAt": "2018-06-29T11:32:38.639568+02:00",
           "UpdatedAt": "2018-06-29T11:32:38.639568+02:00",
           "DeletedAt": null,
           "description": "Child test",
           "parent_id": 1,
           "children": null
        }
    ]
}

实际上,我希望介于两者之间,可以在children数组中选择字段(例如,仅id)。

任何想法,如果可能的话,或者我做错了什么?

0 个答案:

没有答案