Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

type Table1 struct {
    Id      string  `gorm:"primary_key"`
    Table2s []*Table2 //has many
}

type Table2 struct {
    Id      string      `gorm:"primary_key"
    Table1Id string
    Table3s []*Table3   `gorm:"many2many:table2_table3"` //many2many
}

type Table3 struct {
    Id string `gorm:"primary_key"`
}

如上关系,通过table1的Id怎样查询所有table3与之关联的数据?
期望拿到的数据结构是这样的:

Table1:{
    Id:xxx,
    Table2s:[
        {
            Id:xxxxxx,
            Table3s:[
                {Id:x},
                {Id:xx},
                ...
            ]
        },
        ...
    ]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
416 views
Welcome To Ask or Share your Answers For Others

1 Answer

var data []Table1
db.Preload("Table2").Preload("Table2.Table3").Find(&data)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...