源结构上的外键?

huangapple go评论122阅读模式
英文:

Foreign key on source struct?

问题

我正在使用Gorm开始尝试建模以下内容:

  1. type MyLink struct {
  2. gorm.Model
  3. Title string
  4. Url string
  5. }
  6. // group of links under a single title
  7. type MyLinkSection struct {
  8. gorm.Model
  9. Title string
  10. Links []MyLink
  11. }
  12. type MyPage struct {
  13. gorm.Model
  14. PageUrl MyLink
  15. Artists []MyLinkSection
  16. }

如你所见,我希望能够将相同的结构体MyLink既作为MyPage的外键对象,又作为MyLinkSection的一对多关系。

似乎我需要在MyLink中声明外键ID,这似乎不太可能。

是否有任何方法可以设置这样的表结构?在普通的数据库中,我只需在MyPage中有一个名为my_link_id的字段,MyLinkSection也类似。

英文:

I'm starting with Gorm and trying to model the following:

  1. type MyLink struct {
  2. gorm.Model
  3. Title string
  4. Url string
  5. }
  6. // group of links under a single title
  7. type MyLinkSection struct {
  8. gorm.Model
  9. Title string
  10. Links []MyLink
  11. }
  12. type MyPage struct {
  13. gorm.Model
  14. PageUrl MyLink
  15. Artists []MyLinkSection
  16. }

As you can see I want to be able to refer to the same struct, MyLink as both a foreign keyed object from MyPage but also as a one-to-many from MyLinkSection.

It seems I have to declare the foreign key ID in MyLink which would seem to make this not possible.

Is there any way of setting up tables like this? With a normal DB I'd just have a field in MyPage called my_link_id, with something similar for MyLinkSection.

答案1

得分: 1

似乎可以指定正向关系:

  1. PageUrl MyLink `gorm:"ForeignKey:PageUrlId"`
  2. PageUrl Id uint
英文:

It seems it is possible to specify forward relations:

  1. PageUrl MyLink `gorm:"ForeignKey:PageUrlId"`
  2. PageUrl Id uint

huangapple
  • 本文由 发表于 2017年7月23日 16:28:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/45263055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定