英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论