douti8321 2017-11-02 21:03 采纳率: 0%
浏览 231

如何在GORM中建立一对一关系?

I have a series of categories of a type of Product. There are only 3 of them so I can create a table for each. Lets call them SubProductA, SubProductB and SubProductC. They are distinct enough that storing them in the parent Product table would make a mess.

So naturally, I just allow the primary key to be the foreign key linking back to product for each of these. However, GORM seems to not be able to preload any field like this. Here is what I have (as an example) for one of these:

type SubProductA struct {
  ProductID uint64 `gorm:"primary_key;ForeignKey:ProductID"`
  Product Product
  CreatedAt           time.Time
  UpdatedAt           time.Time
  DeletedAt           *time.Time
}

However, when I run a query like

db.Where("product_id=?", p.ID).Preload("Product").First(&subProduct).Error

The result is:

Can't preload field Product for models.SubProductA.

I suspect this is because I'm not properly identifying the primary key as the foreign key as well. However, I have tried a bunch of different things and I get the same error.

Is there a way to make this work?

  • 写回答

1条回答 默认 最新

  • doudou6719 2017-11-02 21:55
    关注

    To answer my own question for people passing through...

    It seems that GORM has problems with multiple-level one-to-one relationships. For a single level, the example I gave, it works without needing anything more. However, to do a preload on a field that is also a one-to-one with the same key farther up the tree, I needed to do the following:

    type SubSubProductA struct {
      SubProductID uint64 `gorm:"primary_key"`
      SubProductA SubProductA `gorm:"ForeignKey:SubProductID`"
      CreatedAt           time.Time
      UpdatedAt           time.Time
      DeletedAt           *time.Time
    }
    

    In other words, the ForeignKey part goes on the object itself. This fixed the preloading for me. Hope this helps someone. The GORM documentation is very sparse for anything but the common cases.

    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line