doubanduo7620 2018-11-16 17:21
浏览 103
已采纳

使用ORM将任意数据检索到嵌套对象中

I am attempting to develop an api in go, to allow the user to specify an arbitrary data structure, and easily set up endpoints that perform CRUD operations on an auto generated postgres database, based on the structure that they define.

For now, I have been using gorm, and am able to have a database automatically generated based on a user-defined set of structs, that support all types of relations (has one, one to many, etc.). I am also able to insert into the generated database, when JSON is sent in through the endpoints.

The issue I have discovered, is when I try to receive the data. It seems where many of the go ORMs fall short on, is mapping data from all tables back into the nested structs of the parent struct.

For example, if the user defines:

type Member struct {
    ID          string      
    FirstName   string      
    Hometown    Hometown    `gorm:"ForeignKey:MemberRefer"`
}

type Hometown struct {
    ID              string
    City            string
    Province        string
    MemberRefer     string
}

The database creates the tables:

Members

  • id
  • first_name

Hometowns

  • id
  • city
  • province
  • member_refer

However, when retrieving the data, all that is mapped back is:

{
    "id": "dc2bb591-506f-40a5-a141-bdc0c8410ba1",
    "name": "Kevin Krishna",
    "hometown": {
        "id": "",
        "city": "",
        "province": ""
    }
}

Does anyone know of a go orm that supports this kind of behaviour?

Thanks

  • 写回答

1条回答 默认 最新

  • duanbo5230 2018-11-16 17:28
    关注

    5 sec google search showed me the answer:

    Preloading associations

    Now that you actually have them properly related, you can .Preload() get the nested object you want: db.Preload("GoogleAccount").First(&user)

    Get nested object in structure in gorm

    https://www.google.com/search?q=gorm+nested+struct+golang

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!