2017-07-15 79 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爲好,但它不會傷害如果事實證明你使用它的話。