2017-07-15 42 views
0

想象一下以下模型:Golang GORM选择所有依赖

type (

    Account struct { 
     gorm.Model 

     CustomID string `gorm:"index;unique"` 
     Name string 
     Profiles []*Profiles `gorm:"ForeignKey:AccountID"` 
    } 

    Profile struct { 
     gorm.Model 

     AccountID uint `gorm:"index"` 
     TheFoo *Foo 
     TheDoo *Doo 
    } 

    Foo struct { 
     ProfileID uint `gorm:"index"` 
     Boo string 
    } 

    Doo struct { 
     ProfileID uint `gorm:"index"` 
     Moo string 
    } 
) 

所有我得到整个结构总是失败的尝试。 acc始终只填写帐户数据并且没有配置文件。

我甚至用这个db.Model(&acc).Related(&Profile{})东西,但仍然没有成功。 (可以说,非常糟糕)文档也没有说明这一点。

var acc Account 
db.Find(&acc, "custom_id = ?", myCustomID) 

你会怎么做到这一点?

回答

0

当你调用相关函数时,你可以添加你的代码吗? http://jinzhu.me/gorm/associations.html#has-many什么我看到有很多它应该看起来像这样的文档。

var acc Account 
db.Find(&acc, "custom_id = ?", myCustomID) 
db.Model(&acc).Related(&profiles) 
+0

这实际上有预期的结果,但我本来会期望的是,我已经可以像其他ORM一样组装它。 否则我将不得不迭代配置文件以获得其他关系正确吗? – Danilo

1

我相信你可以使用Preload方法支持NE,即:

account := new(Account) 
db.Preload("Profiles.TheDoo").Preload("Profiles.TheFoo").Find(account, "custom_id = ?", myCustomID) 

我没有检查但如果你确实需要预装Profiles为好,但它不会伤害如果事实证明你使用它的话。