gorm包用于在一个表中建立多对多关系

时间:2019-04-09 06:10:34

标签: go relationship go-gorm

我尝试在Golang中为带有“ gorm” ORM的注释表设置parent_id。但无法获得结果。

这是文档:http://doc.gorm.io/associations.html#many-to-many

这是我的代码:

type Comment struct {
    gorm.Model
    Text string `sql:"type:text;"`
    Comments []Comment `gorm:"many2many:CommentThread;foreignkey:ID;association_foreignkey:ParentID"`
    ParentID uint
}

我用打击代码填充数据库:

    db.Create(&Comment{
        Text: "commente avale sara",
    })
    db.Create(&Comment{
        Text: "commente dovom sara",
    })
    db.Create(&Comment{
        Text: "commente sevom sara",
    })
    db.Create(&Comment{
        Text: "javabe aval sara az sam",
        ParentID: 3,
    })
    db.Create(&Comment{
        Text: "javabe dovom sara az sam",
        ParentID: 3,
    })
    db.Create(&Comment{
        Text:   "commente sevemoe sam",
    })

和打击代码用于打印结果:

var comments Comment
    var child []Comment
    db.First(&comments, 3)
    db.Model(&comments).Related(&child,"CommentThread")
    fmt.Println("comments: ", child)

这是Erorr的结果:

comments:  []

(C:/Go/myProjects/antilicense/app/main.go:264) 
[2019-04-09 10:31:25]  invalid association [CommentThread] 

Process finished with exit code 0

0 个答案:

没有答案