Golang中gorm的自关联关系无法正常使用的问题
Golang中gorm的自关联关系无法正常使用的问题 为什么 GORM 的自引用多级关联对我不起作用
type Comment struct {
gorm.Model
Text string `sql:"type:text;"`
Comments []Comment `gorm:"foreignkey:ID;associatdion_foreignkey:ParentID"`
ParentID uint
PostID uint
UserID uint
}
这是错误信息:
invalid association []
这是我获取结果的代码:
var comments Comment
var child []Comment
db.First(&comments, 3)
db.Model(&comments).Related(&child)
fmt.Println("comments: ", child)
更多关于Golang中gorm的自关联关系无法正常使用的问题的实战教程也可以访问 https://www.itying.com/category-94-b0.html
3 回复
关于是否使用ORM存在两种不同的观点。在我看来,在原生SQL之上再添加一层会带来限制、降低性能并增加额外的学习时间。
但另一方面,也有许多开发者持相反意见。
仅供参考…
更多关于Golang中gorm的自关联关系无法正常使用的问题的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
你写错了 association_foreignkey。
在您的代码中,自关联关系的配置存在问题。GORM的自关联需要使用特定的外键配置。以下是正确的实现方式:
type Comment struct {
gorm.Model
Text string `gorm:"type:text"`
ParentID *uint // 使用指针类型允许NULL值
Children []Comment `gorm:"foreignkey:ParentID"` // 修正关联配置
PostID uint
UserID uint
}
查询代码也需要相应调整:
var comment Comment
// 预加载子评论
db.Preload("Children").First(&comment, 3)
fmt.Println("comment: ", comment)
fmt.Println("children: ", comment.Children)
// 或者使用Joins方式查询
var commentsWithChildren []Comment
db.Joins("LEFT JOIN comments AS children ON children.parent_id = comments.id").
Where("comments.id = ?", 3).
Find(&commentsWithChildren)
主要问题在于:
- 外键配置错误:应该使用
foreignkey:ParentID而不是foreignkey:ID - 移除了无效的
association_foreignkey配置 - 查询时使用
Preload来加载关联数据
正确的完整示例:
package main
import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type Comment struct {
ID uint `gorm:"primarykey"`
Text string `gorm:"type:text"`
ParentID *uint
Children []Comment `gorm:"foreignkey:ParentID"`
PostID uint
UserID uint
}
func main() {
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
db.AutoMigrate(&Comment{})
// 创建测试数据
parent := Comment{Text: "父评论", PostID: 1, UserID: 1}
db.Create(&parent)
child := Comment{Text: "子评论", ParentID: &parent.ID, PostID: 1, UserID: 1}
db.Create(&child)
// 查询父评论及其子评论
var comment Comment
db.Preload("Children").First(&comment, parent.ID)
fmt.Printf("主评论: %s\n", comment.Text)
for i, child := range comment.Children {
fmt.Printf("子评论%d: %s\n", i+1, child.Text)
}
}
这样配置后,自关联关系就能正常工作了。

