源结构上的外键?

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

Foreign key on source struct?

问题

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

type MyLink struct {
    gorm.Model
    Title string
    Url   string
}

// group of links under a single title
type MyLinkSection struct {
    gorm.Model
    Title string
    Links []MyLink
}

type MyPage struct {
    gorm.Model
    PageUrl MyLink
    Artists []MyLinkSection
}

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

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

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

英文:

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

type MyLink struct {
	gorm.Model
	Title             string
	Url               string
}

// group of links under a single title
type MyLinkSection struct {
	gorm.Model
	Title string
	Links []MyLink
}

type MyPage struct {
	gorm.Model
	PageUrl     MyLink
	Artists     []MyLinkSection
}

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

似乎可以指定正向关系:

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

It seems it is possible to specify forward relations:

PageUrl       MyLink `gorm:"ForeignKey:PageUrlId"`      
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:

确定