实体与自身关联,具有一对多关系

Entity association to itself with one-to-many relationships

我使用 GORM 在 Golang 中构建模型关联,我有一个名为 Category 的结构。一个类别可以有很多子类别,它可以有一个父类别:

type Category struct {
 Name string `json:"name"`
 Parent Category `json:"parent_category"`
 ParentGroupID uint `json:"parent_group_id"`
 Children []Category `json:"children_categories"`
}

对于这个结构,我得到了一个错误无效的递归类型类别。我检查了 GORM 文档,但没有找到任何有用的信息。有什么想法可以用 GORM 来模拟这种关系吗?

您必须将 Parent 声明为 *Category(指向 Category 的指针)而不是 Category

type Category struct {
 Name string `json:"name"`
 Parent *Category `json:"parent_category"`
 ParentGroupID uint `json:"parent_group_id"`
 Children []Category `json:"children_categories"`
}

编译器如何知道Parent的大小。指针的大小是已知的,但是包含自身的东西有多大? (并且内部结构也包含自身,内部内部结构也是如此。)

参考: