关于解决数据库拿不到子表的问题
关于解决数据库拿不到子表的问题
这是我的go创建数据库的代码,SubComment是靠ParentCommentID关联起来的
type CommentModel struct {
MODEL
SubComments []*CommentModel `gorm:"foreignKey:ParentCommentID" json:"sub_commnets"`
ParentCommentModel *CommentModel `gorm:"foreignKey:ParentCommentID" json:"comment_model"`
ParentCommentID *uint `json:"parent_comment_id"`
Content string `gorm:"size:256" json:"content"`
DiggCount int `gorm:"size:8;default:0;" json:"digg_count"`
CommentCount int `gorm:"size:8;default:0;" json:"comment_count"`
ArticleID string `gorm:"size:32" json:"article_id"`
User UserModel `json:"user"`
UserID uint `json:"user_id"`
}
在我通过以下方法某一评论表去拿它的子评论表数组时,返回的一直是空
// 先查找指定文章所有的根评论
var rootList []models.CommentModel
err = global.DB.Find(&rootList, "article_id = ? and parent_comment_id is null", cr.ArticleID).Error
if err != nil {
res.FailWithMessage("没有查询到评论", ctx)
return
}
for _, root := range rootList {
global.Log.Info(root.SubComments)
}
解决方法:
需要在使用root.SubComments之前,预加载SubComments
for _, root := range rootList {
global.DB.Preload("SubComments").Take(&root)
global.Log.Info(root.SubComments)
}

浙公网安备 33010602011771号