<p>Hi folks. Back-end web dev question here. Let's take a model like this: </p>
<pre><code>type Allocation struct {
gorm.Model
ContractID uint `json:"contract_id" form:"contract_id"`
Contract Contract
}
</code></pre>
<p>And let's say the Contract looks like this: </p>
<pre><code>type Contract struct {
gorm.Model
Variables Variables
VariablesID uint `gorm:"type:integer;not null" json:"variables_id" form:"variables_id"`
Allocations []Allocation
}
</code></pre>
<p>I want to load my Contract, so I do it like so, correct?</p>
<pre><code>connect.DB.Model(a).Related(&a.Contract)
</code></pre>
<p>Now my a.Contract has a contract loaded in. What if I also want my Contract's Variables? </p>
<pre><code>connect.DB.Model(&a.Contract).Related(&a.Contract.Variables)
</code></pre>
<p>And on and on for however long the chain of relations goes. Feels like I'm doing it wrong. Do you add a method on your models to load in all the relations when you get one from the DB, or am I doing it how you do it? If this is how you do it, where do you put this logic? Load up the models in the controllers first, or...?</p>
<hr/>**评论:**<br/><br/>[deleted]: <pre><p>You should use <a href="http://jinzhu.me/gorm/crud.html#preloading-eager-loading" rel="nofollow">Preload</a></p>
<pre><code>err := DB.
Where("foo = ?", "bar").
Preload("Allocations").
Find(&contract).
Error
</code></pre></pre>diabetesjones: <pre><p>Thank you very much!</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传