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 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。