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

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

报告相同问题?

悬赏问题

  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn